gpt4 book ai didi

node.js - Express-jwt 与黑名单撤销功能一起使用时不设置 req.user

转载 作者:太空宇宙 更新时间:2023-11-04 01:49:39 25 4
gpt4 key购买 nike

我尝试使用express-jwt进行用户身份验证REST API并使用express-jwt-blacklist进行注销。但是当我开始使用黑名单撤销功能时,我得到 express-jwt is not set 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 token 调用用户/详细信息时,我得到的响应为“未经授权的 token ”(未设置 req.user)

最佳答案

创建 token :

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'
});
}

关于node.js - Express-jwt 与黑名单撤销功能一起使用时不设置 req.user,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50192027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com