简体   繁体   English

Nestjs 护照-jwt 忽略 JWT 签名

[英]Nestjs passport-jwt ignore JWT signature

I can't pass any secret here, because it is stored in Redis for each user and I have to parse the token body before I can access the user id to get their secret.我不能在这里传递任何秘密,因为它存储在每个用户的 Redis 中,我必须先解析令牌主体,然后才能访问用户 ID 以获取他们的秘密。 Using nestjs for architecture.使用 nestjs 进行架构。 Are there any elegant solutions without having to write whole copy of the strategy by myself?是否有任何优雅的解决方案而不必自己编写整个策略副本?

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();
    }
  }
}```

Performed a bit more research and found this进行了更多的研究,发现了这一点

      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));
      },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM