0

我正在使用 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);
          });
  }

));

4

1 回答 1

2

您可以创建自定义提取器功能

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);
                });
        })
    );
};

有关更多详细信息,请参阅此答案

于 2020-06-27T09:11:52.290 回答