Nestjs passport-jwt 忽略 JWT 签名

Nestjs passport-jwt ignore JWT signature

我不能在这里传递任何秘密,因为它存储在每个用户的 Redis 中,我必须先解析令牌主体,然后才能访问用户 ID 以获取他们的秘密。使用 nestjs 进行架构。有没有不用自己写整篇攻略的优雅解决方案?

export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private authService: AuthService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: ???,
      passReqToCallback: true,
    });
  }

  async validate(req: any, payload: UserType): Promise<UserType> {
    try {
      const token = ExtractJwt.fromAuthHeaderAsBearerToken()(req);

      const [header, body] = token.split('.');

      const headerJSON = JSON.parse(btoa(header)) as { alg: Algorithm };
      const bodyJSON = JSON.parse(btoa(body)) as UserType;

      const sub = bodyJSON.sub;

      const userId = await this.authService.findUserSecret(sub);

      const jwt = new JwtService({
        secret: userId,
      });

      await jwt.verify(token, {
        algorithms: [headerJSON.alg],
      });

      return payload;
    } catch (e) {
      return Promise.reject();
    }
  }
}```

进行了更多研究并发现了这个

      secretOrKeyProvider(request: any, rawJwtToken: string, done: any) {
        const [, body] = rawJwtToken.split('.');

        const bodyJSON = JSON.parse(btoa(body)) as UserType;

        const { sub } = bodyJSON;

        authService
          .findUserSecret(sub)
          .then(secret => secret || Promise.reject())
          .then(secret => done(null, secret))
          .catch(error => done(error, null));
      },