我使用带有护照Auth JWT的nodejs。我可以创建JWT令牌,但如果我使用passport.authenticate(' jwt')保护我的路线,它就不起作用而且我有错误。
我的错误: TypeError:无法读取属性' _id'未定义的 在JwtStrategy._verify(D:\ Programes \ nodejs \ node \ CRUD_NodeAngular5 \ NodeServer \ config \ passport.js:15:39) 在D:\ Programes \ nodejs \ node \ CRUD_NodeAngular5 \ NodeServer \ node_modules \ passport-jwt \ lib \ strategy.js:110:26 在D:\ Programes \ nodejs \ node \ CRUD_NodeAngular5 \ NodeServer \ node_modules \ passport-jwt \ node_modules \ jsonwebtoken \ verify.js:27:18 at _combinedTickCallback(internal / process / next_tick.js:131:7) at process._tickCallback(internal / process / next_tick.js:180:9)
Passport.js
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var User = require('../models/User');
var config = require('./database');
module.exports = function(passport) {
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeader();
opts.secretOrKey = config.secret;
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
User.findById(jwt_payload.$__._id, function(err, user) {
if (err) {
return done(err, false);
}
if (user) {
done(null, user);
} else {
done(null, false);
}
});
}));
};
登录
router.post('/login', function(req, res) {
User.findOne({ email: req.body.email }, function(err, user) {
if (err) throw err;
if (!user) {
res.send({ success: false, message: 'Authentication failed. User not found.' });
console.log('User not found');
} else {
user.comparePassword(req.body.password, function(err, isMatch) {
if (isMatch && !err) {
var token = jwt.sign(user.toJSON(), config.secret, {expiresIn: 1000 });
var decoded = jwt.decode(token);
console.log(decoded);
res.json({ success: true, token:'JWT ' + token, decoded: decoded });
console.log('Connected : ' + token);
} else {
res.send({ success: false, message: 'Authentication failed. Passwords did not match.' });
console.log('Password is wrong');
}
});
}
});
});
路线仪表板不起作用
router.get('/dashboard', passport.authenticate('jwt', { session: false }), function(req, res) {
res.send('It worked! User id is: ' );
});