我正在使用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);
});
}
));
答案 0 :(得分: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