如何访问JwtToken以在nestjs护照策略中检查黑名单?

时间:2020-09-23 20:48:14

标签: passport.js nestjs passport-jwt

我正在尝试在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;
  }
}

1 个答案:

答案 0 :(得分:0)

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