从回调访问jwtFromRequest

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

我正在学习使用JWT策略的passport.js,我想创建一个注销用户的系统。

我想这样处理:

  1. 当用户注销时,他的令牌存储在我的数据库中,名为InvalidTokens
  2. 每次用户发出受保护的请求时,我都想检查他的令牌是否在表InvalidTokens

问题是我不知道如何在下面的代码中访问字段jwtFromRequest

// passport.js
// File where I store my authentication strategies

// ...

/**
 * Use JWT strategy for all the other requests that need authentication on the
 * server 
 */
var opts = {
  jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
  secretOrKey: 'secret',
}

passport.use('jwt', new JWTStrategy(
  opts,
  async (jwtPayload, done) => {
    try {
      const token = await TokenInvalide.findOne({
        where: {
          Token: '<token_value_I_can\'t_reach>',
        }
      })

      if (token !== null)
        return done(null, false);

      return done(null, jwtPayload.idUtilisateur);

    } catch (e) {
      console.log(e);
      return done(null, false);
    }
  }
));
javascript node.js authentication passport.js passport-jwt
1个回答
1
投票

According to the doc你可以通过将request设置为true来将passReqToCallback对象传递给回调

没有测试过,但应该是正确的方向

var opts = {
  jwtFromRequest: ExtractJWT.fromAuthHeaderAsBearerToken(),
  secretOrKey: 'secret',

  passReqToCallback: true // <----- Add this

}

passport.use('jwt', new JWTStrategy(
  opts,
  async (req, jwtPayload, done) => {

    const rawJWTToken = req['Authorization'].split(' ')[1]

    ...
  }
));
© www.soinside.com 2019 - 2024. All rights reserved.