我正在使用passport.js JWT策略对我的MEAN-Stack应用进行身份验证。不安全的路由正常工作,但我无法使安全的路由正常工作。即使我坚持使用文档,他们仍然会返回Internal Server Error 500。这是代码:
在应用路由之前先在index.js中初始化:
server.use(passport.initialize());
我的password.js设置文件:
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/db');
module.exports = function(passport) {
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findOne({_id: jwt_payload._id}, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
}
});
}));
};
我的路线无效:
const express = require('express');
const router = express.Router();
const config = require('../config/db');
const jwt = require('jsonwebtoken');
const User = require('../models/user');
require('../config/passport');
const passport = require('passport');
router.get('/profile', passport.authenticate('jwt', {session: false}), function(req,
res){
res.json(user);
});
module.exports = router;
我的令牌已正确设置,因为我可以手动对其进行解码。
我如何从角度调用此路由(我知道我实际上不需要呼叫本身的userId参数):
public getProfile(userId) : any{
let httpOptions = {
headers: new HttpHeaders({ 'Authorization': `Bearer ${this.token}` })
};
this.http.get('http://localhost:8080/api/v1/profile', httpOptions).subscribe(res => {
console.log('got the profile for user with id: ' + userId + '=> ' + res);
return res;
}, err => {
console.log(err);
});
}
感谢您的帮助。预先感谢您的宝贵时间!
编辑:猫鼬日志
Mongoose: users.findOne({ _id: ObjectId("5bcf1218cace7d1168a23672") }, {
projection: {} })
GET /api/v1/profile 500 4.579 ms - 5
OPTIONS /api/v1/profile 204 0.097 ms - 0
{ _id: '5bcf1218cace7d1168a23672',
email: '12@email.com',
password: '$2a$10$z8li41jQMESsmbIyQUsPfO6VkYjOyO/ybj4lW04VGUkJmlShydBN.',
name: '12',
age: 12,
gender: 'male',
description: '12',
question: '12',
__v: 0,
iat: 1540419498 }
Mongoose: users.findOne({ _id: ObjectId("5bcf1218cace7d1168a23672") }, {
projection: {} })
GET /api/v1/profile 500 3.995 ms - 5
答案 0 :(得分:0)
我在命中点上添加了单行注释,验证了这些点并进行了相应注释,以进行进一步调试。确认/api/v1/
是快速根路由。
passport.js
const JwtStrategy = require('passport-jwt').Strategy,
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('../models/user');
const config = require('../config/db');
module.exports = function(passport) {
let opts = {
secretOrKey: config.secret,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
issuer: 'TODO', // configure issuer
audience: 'TODO' // configure audience
};
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
console.log(jwt_payload); // confirm _id is defined
User.findOne({ _id: jwt_payload._id }, function(err, user) {
if (err) {
return done(err, false);
}
if (!user) {
return done(null, false);
}
return done(null, user);
});
}));
};
route.js
const express = require('express');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../config/db');
const User = require('../models/user');
const router = express.Router();
require('../config/passport');
router.get('/profile', passport.authenticate('jwt', { session: false }), function(req, res) {
res.json(req.user); // use req.user not user
});
module.exports = router;