使用express和angular 5构建CMS 我尝试设置护照JWT身份验证,但如果我尝试访问后端的受保护路由,我会一直收到错误。
我搞了 jwt_payload ,那里没有用户。 所以,虽然我发送的标题有问题,但它看起来很好,"授权" header包含令牌。
我真的很无奈
这是我的设置:
护照策略
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});
});
角度服务
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'});
}
});
});
});
那是来自req
的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' ]
答案 0 :(得分:0)
尝试 console.log(JSON.stringify(jwt_payload)); 并检查是否有一个名为“ _id”的属性。
答案 1 :(得分:0)
内部:
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。
这解决了我的问题。希望对别人有帮助。