我使用express-jwt和logout使用express-jwt-blacklist尝试了用户身份验证REST API。但是当我开始使用黑名单撤销功能时,我得到快递-jwt没有设置req.user下面是我的代码:
const express = require("express")
var expressJwt = require('express-jwt');
var blacklist = require('express-jwt-blacklist');
const bodyParser = require('body-parser')
const app = express()
app.locals.authSecret="MySuperSecretKey"
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(expressJwt({
secret: app.locals.authSecret,
isRevoked: blacklist.isRevoked,//When I remove this option details is working
credentialsRequired: false
}).unless(function(r) {
allowed = [
'/user/signup',
'/user/login'
]
return allowed.indexOf(r.originalUrl) >= 0
}))
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
res.json({success:false,error:"Unauthorized access token"})
return;
}
next()
});
app.get('user/login',function(req,res){
var username = sanitizer.sanitize(req.body.username);
var password = sanitizer.sanitize(req.body.password);
User.findOne({username:username}, function(err,docs){
if(err)
res.json({success:false,error:"Error in database connection"})
}).cursor().on("data",function(doc)
{
bcrypt.compare(password, doc.password, function(err, same) {
if(err || !same) {
res.json({success:false,error:"Wrong username or password"})
} else {
var userId = doc._id
req.user = userId
console.log(req.user)
res.json({success:true,authToken: jwt.sign({id: userId},req.app.locals.authSecret, {expiresIn: '10d'})})
}
})
})
})
//Get user details by passing JWT Token in header
app.get('user/details',function(req,res){
if(req.user) {
User.findOne({_id:req.user.id}, function(err,docs){
if(err)
res.json({success:false,error:"Error in database connection"})
}).cursor().on("data",function(doc)
{
var user={
firstName:doc.firstName,
lastName:doc.lastName,
username:doc.username,
gender:doc.gender,
email:doc.email,
mobile:doc.mobile,
}
res.json({success:true,data:user})
})
} else {
res.json({success:false,error:"Unauthorized access"})
}
})
//Logout
app.get('user/logout',function(req,res){
blacklist.revoke(req.headers.authorization)
res.json({success:true,message:"You have been successfully logged out"})
})
app.listen(8080, function() {
console.log("Started server at 8080..")
});
代码正常工作直到登录。但是当我使用JWT令牌调用用户/详细信息时,我得到的响应为“未授权令牌”(未设置req.user)
答案 0 :(得分:0)
创建令牌:
jwt.sign(
{
user:email,
id:id,
account: account_id,
permissions: permissions
},
process.env.SECRET_KEY,
{ expiresIn: 60,
subject: email
}
注销:
function logout(req, res) {
blacklist.revoke(req.user);
res.status(200).json({
status: 'success'
});
}