Passport JWT 适用于空负载

Passport JWT works with empty payload

我已经为 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)
}

但是当我传递空的或无效的令牌 Passport 时,只需传递这个

(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 调用 return 类型,但如果没有匹配 ID,它会引发错误吗?

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

如果它没有引发错误但 return 为 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();