我使用 json web 令牌获得了电子邮件和密码的令牌,但是当我输入这个 http://localhost:3001/users/profile url 作为发布请求并在邮递员工具中将令牌作为 Authorizaton 标头传递时,我总是未经授权。
我的 app.js 文件是,
const express = require('express')
const app = express()
const path = require('path');
const mongoose =require("mongoose")
const config =require("./config/database")
const bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
const users =require("./routes/users")
const passport =require("passport")
app.use(passport.initialize());
app.use(passport.session());
require("./config/passport-jwt")(passport)
const port = 3001
app.use(express.static(path.join(__dirname,"public")))
app.use("/users",users)
mongoose.connect(config.url).then(()=>{
console.log("database is connected")
},err=>{
console.log("database is not connected",err)
})
app.listen(port, () => {
console.log(`listing to port : ${port}`)
})
我的 passport-jwt.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) {
User.findUserById({_id: 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
}
});
}));
}
我的 routes.js 文件是,
const express = require('express')
const router =express.Router()
const User =require("../models/user")
const jwt = require('jsonwebtoken');
const config =require("../config/database")
const passport =require("passport")
router.post("/login",(req,res)=>{
const email =req.body.email
const password =req.body.password
User.checkEmail(email,(err,user)=>{
if(err) throw err
if(!user){
res.status(404).json({msg:"user not found"})
}
User.checkPassword(password,user.password,(err,match)=>{
if(err) throw err
if(match){
const token = jwt.sign({user},config.secret,{expiresIn:1233333});
res.status(200).json({
token:"JWT"+token,
user:{
id:user._id,
name:user.name,
email:user.email,
password:user.password,
}
})
}
})
})
})
router.post('/profile', passport.authenticate('jwt',{ session: false }),
function(req, res) {
res.json({user:req.user})
}
);
我的 model.js 文件是,
const mongoose =require("mongoose")
const schema =mongoose.Schema
const bcrypt = require('bcryptjs');
const userSchema =new schema({
username:{type:String,required:true},
name:{type:String,required:true},
email:{type:String,required:true},
password:{type:String,required:true},
})
const User = module.exports =mongoose.model("User",userSchema)
module.exports.saveData =function (userData,callback) {
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(userData.password, salt, function(err, hash) {
userData.password=hash
if(err) throw err
userData.save(callback)
});
});
}
module.exports.checkEmail=function (email,callback) {
const query ={email:email}
User.findOne(query,callback)
}
module.exports.checkPassword=function (plainPassword,hash,callback) {
bcrypt.compare(plainPassword, hash, function(err, res) {
if (err) throw err
if(res){
callback(null,res)
}
});
}
module.exports.findUserById =function (id,callback) {
User.findOne(id,callback)
}
我的 database.js 文件是,
module.exports ={
"url":"mongodb://localhost:27017/authapp",
"secret" :"secretkey"
}
**请帮我解决这个问题,