【问题标题】:How to get access to JwtToken to check with blacklist within nestjs passport strategy?如何访问 JwtToken 以检查 nestjs 护照策略中的黑名单?
【发布时间】:2021-01-10 03:06:22
【问题描述】:

我正在尝试在 JWTStrategy 中检查列入黑名单的 JWT 令牌。 jwtFromRequest 不带异步功能,所以我不能在那里检查。

validate 函数允许访问 JWT 有效负载而不是令牌。

下面是我的示例代码。

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(
    private readonly configService: ConfigService<AppJWTSettings>,
    @Inject(CACHE_MANAGER) private readonly cache: Cache,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), // Returns the encoded JWT string or null.
      ignoreExpiration: false, // validate the expiration of the token.
      // https://docs.nestjs.com/techniques/authentication#implementing-passport-jwt
      // PEM-encoded public key
      secretOrKey: configService.get<string>('JWT_PUBLIC_KEY'),
      algorithms: ['RS256'],
    });
  }

  /**
   * Passport will build a user object based on the return value of our validate() method,
   * and attach it as a property on the Request object.
   *
   * @param payload JWT payload
   */
  async validate(payload: JwtPayload): Promise<JwtUser> {
    const user = { id: payload.sub, iat: payload.iat };
    return user;
  }
}

【问题讨论】:

    标签: passport.js nestjs passport-jwt


    【解决方案1】:

    创建新令牌时,我将令牌存储在 cookie 中并通过 AJAX 调用传递令牌,有时通过查询字符串请求传递它。您应该能够通过 cookie(标头)、查询字符串等传递用户使用的任何令牌...在控制器上,对其进行验证,如果列入黑名单,则在未经授权的情况下返回重定向 url 或字符串,并通过 JavaScript 重定向。

    【讨论】:

    • 在控制器中验证不遵循 DRY 方法。在每个受保护的路由中,都需要添加此检查。我什至可以创建一个单独的 Guard 来检查列入黑名单的 JWT,并在 UseGuards 中作为额外的保护传递。我希望在这个 Guard 中解决问题。
    • 通常,每个策略的 validate() 方法的唯一显着区别是您如何确定用户是否存在并且是否有效。例如,在 JWT 策略中,根据需求,我们可能会评估解码后的 token 中携带的 userId 是否与我们的用户数据库中的记录匹配,或者与已撤销的 token 列表匹配。这是 NestJs 官方文档的摘录。 docs.nestjs.com/techniques/…我正在寻找他们推荐的匹配已撤销令牌的方式。
    猜你喜欢
    • 2022-08-12
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2015-03-20
    • 2020-10-21
    • 2022-12-24
    • 1970-01-01
    • 2022-11-04
    相关资源
    最近更新 更多