0

我不能在这里传递任何秘密,因为它为每个用户存储在 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();
    }
  }
}```
4

1 回答 1

0

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

      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));
      },
于 2020-09-06T02:19:33.480 回答