【问题标题】:How to get a rawJWT string in passport-jwt?如何在 passport-jwt 中获取 rawJWT 字符串?
【发布时间】:2020-04-01 03:51:00
【问题描述】:

我正在使用 Express.js、Passport.js。 Jsonwebtoken 我在数据库中保存了一个 JWT 编码的令牌。

我想用 Bearer 检查加密的 JWT。

JwtStrategy 允许我们接收 jwtPayload 对象。

但我需要得到一个加密字符串。 该文档包含 rawJwt,但如何获取加密字符串?如何提取?

passport.use(new JwtStrategy({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey   : config.secretOrKey
  },
  function (jwtPayload, cb) {
      return User.find({_id: jwtPayload.user._id, token: token})// compare the token that goes in encrypted form
          .then(user => {
              return cb(null, user);
          })
          .catch(err => {
              return cb(err);
          });
  }

));

【问题讨论】:

    标签: node.js express jwt passport.js passport-jwt


    【解决方案1】:

    您可以创建自定义提取函数

    const jwtExtractor = (req) => {
        let token = null;
        if (req && req.headers) {
            let tokenParts = req.headers.authorization.split(' ');
            // tokenParts tokenParts[0] is schema and tokenParts[1] is credentials
            // test matching schema 
            if (/^Bearer$/i.test(tokenParts[0])) { // use your own schema instead of Bearer 
                token = tokenParts[1];
            }
        }
        // Declare token globally to use it out side the function, eg: as `Bearer ${token}` or as token
        // or you can store it to another global variable, eg: jwtString = req.headers.authorization
        return token;
    };
    

    并作为 jwtFromRequest: jwtExtractor,

    传递
    let opts = {};
    opts.jwtFromRequest = jwtExtractor;
    opts.secretOrKey = 'secret';
    module.exports = (passport) => {
        passport.use(
            new JWTStrategy(opts, (jwtPayload, done) => {
                UserModel.findOne({_id: jwtPayload.id})
                    .then((user) => {
                        // Here you can check the token with the stored token in DB
                        if (user && user.jwtToken === `Bearer ${token}`) {
                            return done(null, jwtPayload);
                        } else return done(null, false);
                    })
                    .catch((err) => {
                        return done(null, false);
                    });
            })
        );
    };
    

    更多详情请参考this answer

    【讨论】:

      猜你喜欢
      • 2023-02-03
      • 2021-07-23
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多