我正在使用平均堆栈开发这个项目管理工具。在那里我需要对内页使用用户限制。如你所知,我们都使用JSON Web令牌来存档这个东西。我可以注册一个新用户,然后可以登录该工具,这一刻我得到了令牌。 (我会截取屏幕截图。)但问题是当我打算读取身份验证标头以验证它无效时。
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
上面提到的方法用于提取令牌,我得到的日志说明未知的身份验证策略“Bearer”。请帮助我解决这个问题。请参考以下代码以找到解决方案。
passport.js:
const JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
const config = require('./database');
const User = require('../models/user')
const opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = config.secret;
module.exports = function (passport) {
passport.use(new JwtStrategy(opts, function (jwt_payload, done) {
console.log(jwt_payload);
User.findUserById(jwt_payload._doc._id, function (err, user) {
if (err) {
return done(err, false);
}
if (user) {
return done(null, user);
} else {
return done(null, false);
// or you could create a new account
}
});
}));
}
app.js
const express = require('express');
const path = require("path");
const bodyparser = require("body-parser");
const cors = require("cors");
const passport = require("passport");
const mongoose = require("mongoose");
const config = require('./config/database');
mongoose.connect(config.database);
mongoose.connection.on('connected',()=>{
console.log("connected to database"+config.database);
});
mongoose.connection.on('error',(err)=>{
console.log("database error!"+err);
});
const app = express();
//passport middleware
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
const users = require('./routes/users');
const port = 8000;
app.use(cors());
app.use(express.static(path.join(__dirname,'public')));
app.use(bodyparser.json());
app.use('/users',users);
app.get('/',function (req,res) {
res.send("Welcome!");
});
app.listen(port,function () {
console.log("server started!"+port);
});
模特 - > user.js的
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../config/database');
// user schema
const UserSchema = mongoose.Schema({
firstname:{type:String,required: true},
lastname: {type:String,required: true},
username: {type:String,required: true},
email: {type:String,required: true},
password: {type:String,required: true},
role: {type:String,required: true}
});
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.getUserByUsername = function (username, callbcak) {
//
// const query = {username: username}
// User.findOne(query, callback);
// }
module.exports.addUser = function (newUser, callback) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(newUser.password, salt, function(err, hash) {
newUser.password = hash;
newUser.save(callback);
if(err) throw err;
});
});
}
module.exports.passwordCheck = function (candidatePassword,hash,callback) {
bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
if(err)throw err;
if(isMatch){
callback(null,isMatch);
}
});
}
module.exports.findUserById = function () {
User.findOne(id,callback);
}
routes-> users.js
const express = require('express');
const router = express.Router();
const User = require('../models/user');
const passport = require('passport');
const jwt = require('jsonwebtoken');
const config = require('../config/database');
router.post("/register",(req,res)=> {
//res.send("REGISTER");
let newUser = new User({
firstname: req.body.firstname,
lastname: req.body.lastname,
username: req.body.username,
email: req.body.email,
password: req.body.password,
role: req.body.role
});
User.addUser(newUser,(err,user)=>{
if(err){
res.json({state: false,msg:"fail"});
}
if(user){
res.json({state: true,msg:"success"});
}
});
});
router.post("/login",(req,res)=> {
// res.send("LOGIN");
const username = req.body.username;
const password = req.body.password;
User.getUserByUsername(username, (err, user)=> {
if(err) throw err;
if(!user){
return res.json({state:false,msg:"User not found"});
//console.log(user);
}
User.passwordCheck(password, user.password, (err,isMatch)=>{
if(err) throw err;
if(isMatch){
const token = jwt.sign(user.toJSON(), config.secret, {
expiresIn:7200 // seconds for two hours
});
res.json({
state:true,
token:"Bearer "+token,
user:{
id: user._id,
firstname: user.firstname,
lastname:user.lastname,
username: user.username,
email: user.email
}
});
}else{
return res.json({state:false,msg: "Wrong Password!"});
}
});
});
});
router.post('/profile', passport.authenticate('Bearer', { session: false }),(req, res)=> {
//res.json({user:res.user});
res.send("profile");
}
);
router.get("/list",(req,res)=> {
res.send("LIST");
});
router.put("/update",(req,res)=> {
res.send("UPDATE");
});
router.get("/count",(req,res)=> {
res.send("COUNT");
});
module.exports = router;
的package.json
[{
"name": "pmt",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node app"
},
"dependencies": {
"express": "*",
"mongoose": "*",
"bcryptjs": "*",
"cors": "*",
"jsonwebtoken": "*",
"body-parser": "*",
"passport": "*",
"passport-jwt": "*"
},
"author": "cheshan",
"license": "ISC"
}][1]
请参阅以下屏幕截图: