我使用 Express 和 Angular 5 构建 CMS 我尝试设置 Passport JWT 身份验证,但如果我尝试访问后端的 protected 路由,我会不断收到错误。
我登录了jwt_payload,但那里没有用户。 所以我虽然发送的 header 有问题,但看起来很好,“授权” header 包含 token 。
我真的很无助
这是我的设置:
Passport 策略
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/database');
module.exports = function(passport){
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderWithScheme('jwt');
opts.secretOrKey = config.secret;
opts.passReqToCallback = true;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload.user._id, (err, user) => {
if(err){
return done(err, false);
}
if(user){
return done(null, user);
} else {
return done(null, false);
}
});
}));
}
路线
// Profile
router.post('/profile', passport.authenticate('jwt', {session: false}), (req, res, next) => {
res.json({user: req.user});
});
还有 Angular 服务
getProfile(){
let headers = new Headers();
this.loadToken();
headers.append('Authorization', this.authToken);
headers.append('Content-Type', 'application/json');
console.log(headers)
return this.http.get(API_URL + '/users/profile', {headers : headers})
.map(res => res.json());
}
身份验证/登录
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user) => {
if(err) throw err;
if(!user){
return res.json({success: false, msg: 'User not found'});
}
User.comparePassword(password, user.password, (err, isMatch) => {
if(err) throw err;
if(isMatch){
const token = jwt.sign({user}, config.secret, {
expiresIn: 604800 // 1 week
});
res.json({
success: true,
token: 'JWT '+ token,
user: {
id: user._id,
username: user.username,
email: user.email,
firstname: user.firstname,
lastname: user.lastname,
role: user.role
}
});
} else {
return res.json({success: false, msg: 'Wrong password'});
}
});
});
});
这就是请求中的 jwt_payload
headers:
{ host: 'localhost:8080',
connection: 'keep-alive',
'content-length': '0',
authorization: 'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7Il9pZCI6IjVhNWUxYzhlYTI3OWJiMDAyMGZmM2Q5NCIsInVzZXJuYW1lIjoiYWRtaW4iLCJlbWFpbCI6Im1vcm96LmEyNEBnbWFpbC5jb20iLCJmaXJzdG5hbWUiOiJBbGV4IiwibGFzdG5hbWUiOiJNb3JveiIsInBhc3N3b3JkIjoiJDJhJDEwJEdXdk5uVEFtRVVjVEY5SDdtaHg4aE8waHFUaVhqU1oycVVUZkFXTzdGOEE5amZDNXFXT015IiwiX192IjowLCJyb2xlIjoiYWRtaW4ifSwiaWF0IjoxNTE2MTIzNDY5LCJleHAiOjE1MTY3MjgyNjl9.X7iVs6iGrL1NbSfxxNAUBOXV4M5fITFPvcoRzQ6NPnU',
'postman-token': 'ac9c9f81-3e51-f7af-2203-7022d13359cf',
'cache-control': 'no-cache',
origin: 'chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop',
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'content-type': 'application/json',
accept: '*/*',
'accept-encoding': 'gzip, deflate, br',
'accept-language': 'he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7' },
rawHeaders:
[ 'Host',
'localhost:8080',
'Connection',
'keep-alive',
'Content-Length',
'0',
'Authorization',
'JWT eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7Il9pZCI6IjVhNWUxYzhlYTI3OWJiMDAyMGZmM2Q5NCIsInVzZXJuYW1lIjoiYWRtaW4iLCJlbWFpbCI6Im1vcm96LmEyNEBnbWFpbC5jb20iLCJmaXJzdG5hbWUiOiJBbGV4IiwibGFzdG5hbWUiOiJNb3JveiIsInBhc3N3b3JkIjoiJDJhJDEwJEdXdk5uVEFtRVVjVEY5SDdtaHg4aE8waHFUaVhqU1oycVVUZkFXTzdGOEE5amZDNXFXT015IiwiX192IjowLCJyb2xlIjoiYWRtaW4ifSwiaWF0IjoxNTE2MTIzNDY5LCJleHAiOjE1MTY3MjgyNjl9.X7iVs6iGrL1NbSfxxNAUBOXV4M5fITFPvcoRzQ6NPnU',
'Postman-Token',
'ac9c9f81-3e51-f7af-2203-7022d13359cf',
'Cache-Control',
'no-cache',
'Origin',
'chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop',
'User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
'Content-Type',
'application/json',
'Accept',
'*/*',
'Accept-Encoding',
'gzip, deflate, br',
'Accept-Language',
'he-IL,he;q=0.9,en-US;q=0.8,en;q=0.7' ]
最佳答案
内部:
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload.user._id, (err, user) => {
if(err){
return done(err, false);
}
if(user){
return done(null, user);
} else {
return done(null, false);
}
});
}));
更改:
User.getUserById(jwt_payload._id, (err, user) => {
原因:
console.log(jwt_payload.user._id)
未定义
但是
console.log(jwt_payload._id)
将为您提供用户 ID。
这解决了我的问题。希望它对某人有帮助。
关于node.js - Passport JWT : Cannot read property '_id' of undefined in MEAN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48286961/