如何检查passportjs中的token是否过期

问题描述 投票:0回答:1

我正在使用 Passport JwtStrategy 来验证项目中的令牌,但它为每个错误发送相同的错误消息“未经授权”

如果令牌过期,它也仅发送“未经授权”状态,但我需要获取令牌过期状态

有没有办法实现这个逻辑

const passport = require("passport")
const JwtStrategy = require("passport-jwt").Strategy,
ExtractJwt = require("passport-jwt").ExtractJwt
const opts = {}
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken()
opts.secretOrKey = JWT_SECRET


passport.use(
   new JwtStrategy(opts, function (jwt_payload, done) {
    UserID.findOne({ id: jwt_payload._id }, function (err, id) {
      if (err) {
        return done(err, false)
      }
      if (id) {
        return done(null, id)
      } else {
        return done(null, false)
      }
    })
  })
)
javascript node.js jwt passport.js
1个回答
0
投票

使用此中间件发送自定义令牌过期消息:

  export const auth = (req, res, next) => {
    passport.authenticate("jwt", { session: false }, async (error, token) => {
        if (error || !token) {
            console.log("error", error);
            res.status(401).json({ msg: "token expired" });
        } else {
            next();
        }
        
    })(req, res, next);
};
© www.soinside.com 2019 - 2024. All rights reserved.