【问题标题】:How to parse a JWT with express?如何用 express 解析 JWT?
【发布时间】:2020-08-14 11:16:30
【问题描述】:

我想访问我用 node.js 和护照读出的 JWT 的正文 json。

const passport = require('passport');
passport.use(new JWTStrategy(services.uaa));
app.use(passport.initialize());
app.use(passport.authenticate('JWT', {session: false}));

app.use(checkAuth);
function checkAuth(req: express.Request, res: express.Response, next: express.NextFunction) {
  console.log(req);
  return next();
}

当我简单地记录 req 时,它看起来并不像 json。所以我想知道,如何将 req 对象解析为 json?你有什么提示吗?谢谢!

【问题讨论】:

    标签: node.js express jwt


    【解决方案1】:

    您正在使用 passportjs 和 passport-jwt 。再看一下文档,该策略如何从请求中“提取” JWT 令牌(尤其是随附的“有效负载”)。 Passport-JWT Documentation

    const JwtStrategy = require('passport-jwt').Strategy,
          ExtractJwt = require('passport-jwt').ExtractJwt;
    
    const opts = {
       jwtFromRequest : ExtractJwt.fromAuthHeaderAsBearerToken(),
       secretOrKey : 'secret',
       issuer : 'accounts.examplesoft.com',
       audience : 'yoursite.net'
    }
    
    passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
    
        // jwt_payload is the payload that you earlier included 
        // in the jwt token, when you created the jwt token.
    
        // Here you can verify the request,
        // For example, check database if user exists. 
    
        User.findOne({id: jwt_payload.sub}, function(err, user) {
            if (err) {
                return done(err, false);
            }
            if (user) {
                return done(null, user);
            } else {
                return done(null, false);
                // or you could create a new account
            }
        });
    }));
    

    有了这个,您通常不需要额外的“checkAuth”功能。像这样使用它:

    app.use(passport.authenticate('JWT', {session: false}));
    
    // OR
    
    app.post('/protected', passport.authenticate('JWT', {session: false}), (req, res) => {
    
       // this will only fire when authentication was successfull
       // req.user will hold whatever you return in the callback from
       // the strategy function. 
    
    });
    
    

    【讨论】:

      【解决方案2】:

      reqRequest 类型的复杂 Express 对象。 如果要访问大部分时间通过 JWT 的标头,则需要使用:

      req.get('Authorization') // or any other header: 'Content-Type', etc
      

      【讨论】:

      • 酷!当然,正如其他人的回答中提到的,当您使用 Passport 的 JWT 实现时,您可能不需要直接访问令牌,您可能可以依赖 Passport 自己的方法。
      猜你喜欢
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 2017-10-21
      • 2014-11-08
      • 2017-04-19
      • 2019-07-11
      • 2015-01-04
      • 2014-08-28
      相关资源
      最近更新 更多