0
所以我得到了這個策略來提取jwt和從請求返回用戶。這是代碼:護照JWT沒有返回正確的用戶
module.exports = function(passport) {
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.JWT_SECRET;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
console.log('PAYLOAD RECEIVED: ')
console.log(jwt_payload)
User.findOne({id: jwt_payload.id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
console.log('USER ' + user.username)
done(null, user);
} else {
console.log('ELSE')
done(null, false);
}
});
}));
};
無論有效載荷是我總是從數據庫中獲得第一個用戶。 我看到所有的教程使用jwt_payload.id
,但當我做console.log(jwt_payload.id)
它返回undefined,當我試圖提取這樣的ID這樣jwt_payload._doc._id
我得到正確的ID時,我做console.log
但用戶沒有找到。這是代碼爲:
module.exports = function(passport) {
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = process.env.JWT_SECRET;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
console.log('PAYLOAD RECEIVED: ')
let id = jwt_payload._doc._id
console.log(id)
User.findOne({id: id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
console.log('USER ' + user.username)
done(null, user);
} else {
console.log('USER NOT FOUND')
done(null, false);
}
});
}));
};
輸出是: 有效載荷RECEIVED: 59a44431fcd0a9495f64f94c(這是正確的ID) 找不到用戶