护照 JWT 适用于空有效载荷



我已经初始化了JWT的策略:

const jwtStrategyOptions = {
  jwtFromRequest: ExtractJwt.fromHeader('x-access-token'),
  secretOrKey: 'publicKey',
}
passport.use(
  new JwtStrategy(
    jwtStrategyOptions,
    (payload, done) => {
      MySQL.Users.readOne(['id'], { id: payload.userId })
      .fork(
        error => {console.log(error)
          done(error)},
        user => {
          console.log(user)
          done(null, user)}
      )
    }
  )
)

和中间件:

const isAuthenticated: RequestHandler = (req, res, next) => {
  passport.authenticate(
    'jwt',
    { session: false, failWithError: true },
    (error, user) => {
      //error is null when I pass empty payload
      if (error) {
        return next(error)
      }
      req.user = user
      return next()
    }
  )(req, res, next)
}

但是当我通过空或无效令牌护照时,只需通过这个

(payload, done) => {
  MySQL.Users.readOne(['id'], { id: payload.userId })
  .fork(
    error => {console.log(error)
      done(error)},
    user => {
      console.log(user)
      done(null, user)}
  )
}

步骤和代码执行next()函数。我可以以某种方式检测到有效负载无效或为空吗?

我不太确定 MySQL 调用返回类型,但如果没有任何与 id 匹配的内容,它会引发错误吗?

(payload, done) => {
  MySQL.Users.readOne(['id'], { id: payload.userId })
  .fork(
    error => {console.log(error)
      done(error)},
    user => {
      console.log(user)
      done(null, user)}
  )
}

如果它没有引发错误但返回 null 或空值,则需要在"success"回调函数中检查它,因为在这种情况下,它将使用空值调用done(null, user)

根据您的评论,这可能会有所帮助,我用来检查令牌过期错误的一些代码:

    passport.authenticate('jwt',
        {session: false},
        //we need this callback to return information on why it's failing
        //err is not populated, but 'info' is...
        (err, user, info) => {
            if (err) {
                return next(err);
            }
            //if we couldn't authenticate the user, check why
            //401 is used when no token or random information is provided
            //403 is used when a well-formed token is provided, but it has expired thus not valid anymore
            if (!user) {
                if (info.name === 'TokenExpiredError') {
                    return res.status(403).send(info.name);
                }
                else {
                    return res.status(401).send(info.message);
                }
            }
            req.user = user;
            return next();

最新更新