【问题标题】:using jwt with jwt-express with middleware in express js在 express js 中将 jwt 与 jwt-express 与中间件一起使用
【发布时间】:2018-04-13 14:05:53
【问题描述】:

在express-jwt 主页中介绍了一个从标头或查询中获取 json Web 令牌的功能,我们可以将其用作快速中间件,这就是功能:

app.use(jwt({
secret: 'hello world !',
credentialsRequired: false,
getToken: function fromHeaderOrQuerystring (req) {
if (req.headers.authorization && req.headers.authorization.split(' ')
[0] === 'Bearer') {
    return req.headers.authorization.split(' ')[1];
} else if (req.query && req.query.token) {
  return req.query.token;
}
return null;
}
}));

我像这样使用express.Route():

app.use('/user',userRoute);
app.use('/apps',appsRouter);

我的问题是如何使用getToken() 函数或如何在标头授权中访问token。

提前致谢。

【问题讨论】:

    标签: express jwt express-jwt


    【解决方案1】:

    我终于找到了解决方案。使用中间件(jwt)可以验证标头中的令牌,如果可以在req.user中设置,那么在req.user中,我们拥有已删除jwt的所有信息,根据此:

    默认情况下,解码后的令牌附加到 req.user 但可以 配置了 requestProperty 选项。 jwt({ secret: publicKey, requestProperty: 'auth' });

    【讨论】:

      【解决方案2】:

      我认为,如果我没记错的话,您的路线中需要令牌或解码的令牌。我是这样做的。

      我有一个中间件函数,它将为我解码其中包含用户信息的令牌,然后它将解码的对象添加到 req 对象。

      e.g route
      .put('/update', Middleware.decodeToken, yourCallBackfunction)
      
      decodeToken(req, res, next) {
      
      
                  authorization = req.headers.authorization.replace('Bearer ', ''),
                  decodeToken = Jwt.verify(authorization);
                  //verifies the token
      
                  req.tokenInfo = decodeToken
                  next();
          }
      

      【讨论】:

        猜你喜欢
        • 2020-04-30
        • 2016-03-13
        • 2020-06-07
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 2023-03-20
        • 1970-01-01
        • 2015-07-18
        相关资源
        最近更新 更多