【问题标题】:Access jwtFromRequest from callback从回调中访问 jwtFromRequest
【发布时间】:2019-09-05 17:26:34
【问题描述】:

我正在学习 passport.jsJWT 策略,我想创建一个系统来注销用户。

我想这样处理:

  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】:

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

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

    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]
    
        ...
      }
    ));
    

    【讨论】:

      猜你喜欢
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多