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

Posted

技术标签:

【中文标题】与黑名单撤销功能一起使用时,Express-jwt 未设置 req.user【英文标题】:Express-jwt not setting req.user when used with blacklist revoke function 【发布时间】:2018-10-15 22:49:06 【问题描述】:

我尝试了使用 express-jwt 的用户身份验证 REST API 和使用 express-jwt-blacklist 的注销。但是当我开始使用黑名单撤销功能时,我得到 express-jwt is not setting 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)

【问题讨论】:

【参考方案1】:

创建令牌:

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

【讨论】:

以上是关于与黑名单撤销功能一起使用时,Express-jwt 未设置 req.user的主要内容,如果未能解决你的问题,请参考以下文章

Express-jwt 没有返回任何响应

android涂鸦的撤销功能的性能问题?!

Auth 标头未与 GET 请求一起发送

jsonwebtoken和express-jwt的使用

使用 angular 和 express-jwt 实现刷新令牌

SailsJS - 将sails.io.js 与JWT 一起使用