我想用jwt实施护照授权,但是在运行之后我已经获得了令牌,但是get函数无效。当我删除passport.authenticate它工作正常。如果将passport.authenticate添加到get函数,即使console.log也不起作用。
我的passport.js文件代码
const JwtStrategy = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
const User = require('./../server/models/user');
module.exports = function(passport){
console.log('passport');
let opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken('jwt')
opts.secretOrKey = "secretkey";
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
console.log(jwt_payload);
User.getUserById(jwt_payload._doc._id, (err, user) => {
if(err){
return done(err, false);
}
if(user){
return done(null, user);
}else{
return done(null, false);
}
});
}));
}
api.js(获取功能)
router.get('/profile', passport.authenticate('jwt', {session: false}),
function(req, res){
console.log("prof");
res.json({user: req.user});
});
user.js的(型号)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
var bcrypt = require('bcrypt-nodejs');
const userSchema = new Schema({
username: { type:String, lowercase:true, required:true, unique:true},
password: { type:String, required:true},
email: { type:String, lowercase:true, required:true, unique:true},
});
userSchema.pre('save', function(next){
var user = this;
bcrypt.hash(user.password, null, null, function(err, hash) {
// Store hash in your password DB.
if(err) return next(err);
user.password = hash;
next();
});
})
const User = module.exports = mongoose.model('User', userSchema);
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
}
module.exports.getUserByUsername = function(username, callback){
const query = {username: username};
User.findOne(query, callback);
}
module.exports.comparePassword = function(candidatePassword, hash, callback)
{
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err){
throw err;
}
callback(null, isMatch);
});
}
答案 0 :(得分:0)
当你从邮递员那里复制令牌时,请确保在“JWT'”之后有空格。在令牌的开头。同时将其复制到' / authenticate' API
res.json({
success: true,
token: 'JWT '+token,
user: {
id: resUser._id,
name: resUser.username,
email: resUser.email
}
})