Nodejs fastify/jwt 怎么方便的对路由加上认证

import fp from "fastify-plugin";
import fastifyJwt from "[@fastify](/user/fastify)/jwt";

const jwtPlugin = fp(async function (fastify, options) { fastify.register(fastifyJwt, { secret: “sasdsa312321dasasdas21312ldas”, // 加密密钥 }); fastify.decorate(“authenticate”, async function (request, reply) { try { await request.jwtVerify(); } catch (err) { reply.send(err); } }); });

export default jwtPlugin;

fastify.get( “/user/info”, { onRequest: [fastify.authenticate] }, userController.info );

官方推荐的这样做成一个插件, 然后在路由的 onRequest , 这样每个请求都要写, 有啥办法加在一组路由中, 或者给绝大部分的路由都加上


Nodejs fastify/jwt 怎么方便的对路由加上认证

4 回复

这个中间件是设置全部路由的中间件吧!有啥办法设置一组路由的

通配符模式

在Node.js中使用Fastify和JWT(JSON Web Token)进行路由认证,可以通过中间件来实现。以下是一个简单的示例,展示如何为Fastify路由添加JWT认证。

首先,确保你已经安装了Fastify和相关的JWT插件:

npm install fastify fastify-jwt fastify-plugin jsonwebtoken

然后,你可以设置一个Fastify服务器,并配置JWT认证中间件:

const fastify = require('fastify')({ logger: true });
const fastifyJwt = require('fastify-jwt');
const jwt = require('jsonwebtoken');

const secret = 'your_secret_key'; // 请使用安全的密钥

// 注册JWT插件
fastify.register(fastifyJwt, {
  secret,
  sign: { expiresIn: '1h' }
}).after(() => {
  fastify.addHook('onRequest', (request, reply, done) => {
    const token = request.headers.authorization;
    if (token) {
      token = token.split(' ')[1];
      jwt.verify(token, secret, (err, decoded) => {
        if (err) {
          reply.code(401).send({ message: 'Access denied' });
        } else {
          request.user = decoded;
          done();
        }
      });
    } else {
      reply.code(401).send({ message: 'No token provided' });
      done();
    }
  });
});

// 受保护的路由
fastify.get('/protected', (request, reply) => {
  reply.send({ message: 'Hello, ' + request.user.username });
});

fastify.listen(3000, err => {
  if (err) throw err;
  console.log('Server listening on http://localhost:3000');
});

这个示例中,我们注册了fastify-jwt插件,并在onRequest钩子中验证JWT。如果验证通过,请求继续处理;否则,返回401状态码。

回到顶部