2

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

2 回答 2

0

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

于 2020-09-24T14:09:54.483 回答
0

有一个选项secretOrKeyProvider。这是一个例子:

@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
      secretOrKeyProvider: (
        _request: Request,
        rawJwtToken: any,
        done: (err: any, secretOrKey?: string | Buffer) => void,
      ) => {
        // Check if your token is blocked here!!!
        void isBlocked(rawJwtToken).then(isBlocked => {
          if (isBlocked) {
            done(new Error("This token is blocked"));
          } else {
            done(null, 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;
  }
}
于 2022-02-06T20:38:59.950 回答