我正在使用nodejs mongodb和password-jwt中间件passport.authenticate登录进行身份验证应用程序,身份验证登录正常工作,并且我获得令牌,但是登录后尝试访问用户配置文件时出现错误:邮递员控制台中出现401(未授权)。
这是我的应用程序代码..
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;
passport.use(new JwtStrategy(opts, (jwt_payload, done) => {
User.getUserById(jwt_payload.id, (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 passport = require("passport");
const jwt = require("jsonwebtoken");
const config = require("../config/database");
const User = require("../models/user");
//Register
router.post("/register", (req, res, next) => {
//res.send('REGISTER');
let newUser = new User({
name: req.body.name,
email: req.body.email,
username: req.body.username,
password: req.body.password
});
User.addUser(newUser, (err, user) => {
if (err) {
res.json({ success: false, msg: "Failed to register user" });
} else {
res.json({ success: true, msg: "User registered" });
}
});
});
//Authenticate
router.post("/authenticate", (req, res, next) => {
//res.send('AUTHENTICATE');
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.toJSON(), config.secret, {
expiresIn: 3600 // 1week 604800
});
res.json({
success: true,
token: "JWT " + token,
user: {
id: user._id,
name: user.name,
username: user.username,
email: user.email
}
});
} else {
return res.json({ success: false, msg: "Worng password" });
}
});
});
});
//Profile
router.get("/profile", passport.authenticate('jwt', {session: false}), (req, res, next) => {
// res.send("PROFILE");
res.json({user: req.user._id});
});
module.exports = router;
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
//User Schema
const UserSchema = mongoose.Schema({
name:{
type: String
},
email:{
type: String,
required: true
},
username:{
type: String,
required: true
},
password:{
type: String,
required: true
}
});
const User = module.exports = mongoose.model('User', UserSchema);
//Getting UserById
module.exports.getUserById = function(id, callback){
User.findById(id, callback);
console.log("got user by id");
}
//Gettng UserByUserName
module.exports.getUserByUsername = function(username, callback){
const query = {username: username}
User.findOne(query, callback);
}
//AddUser
module.exports.addUser = function(newUser, callback){
bcrypt.genSalt(10,(err, salt) =>{
bcrypt.hash(newUser.password, salt,(err, hash) =>{
if(err) throw err;
newUser.password = hash;
newUser.save(callback);
console.log("new user has been added");
});
});
}
//Login or AUTHENCATION
module.exports.comparePassword = function(candidatePassword, hash, callback){
bcrypt.compare(candidatePassword, hash, (err, isMatch) => {
if(err) throw err;
callback(null, isMatch);
console.log("compare pwd complete");
});
}
任何帮助都受到高度赞赏。
答案 0 :(得分:0)
仅返回token
中的/authenticate
token: "JWT " + token, to
token: token,
登录后的请求需要设置标题:
Authorization:Bearer {token}