【问题标题】:Authenticate Google JWT in NestJs在 NestJs 中验证 Google JWT
【发布时间】:2021-02-09 20:54:58
【问题描述】:

我有一个前端应用程序(角度)。 我正在对 nestjs 后端进行休息调用。

这个休息调用需要一个不记名令牌。 我有来自谷歌的不记名令牌。

但是当我使用它时,我得到了未经授权。

据我了解,我需要获取 google 的密钥。 我读到我从 .well-known 获得了密钥,但我不知道这是哪里。

以下是我的护照策略,我遇到并尝试了一些变化。

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {

  constructor(
    @InjectRepository(UserRepository)
    private userRepository: UserRepository,
    private configService: ConfigService){

super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: '.well=known URI (I think)',
      }),

      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      issuer: 'https://accounts.google.com',
      algorithms: ['RS256'],
    });
  }

  async validate(payload) {
    console.log(payload)
    const { email } = payload;
    const user = await this.userRepository.findOne({ email });

    if(!user || !user.isActive) {
      throw new UnauthorizedException();
    }

    return user;
  }
}

请帮忙。

谢谢。

【问题讨论】:

    标签: authentication jwt token nestjs google-authentication


    【解决方案1】:

    我解决了这个问题。由于某种原因,它在我使用的克隆存储库中不起作用,但重新克隆后,它起作用了。

    下面是实现。

    ->'KEYS_URI':这将是一个 uri,其中包含您用来验证令牌的密钥。例如:谷歌-https://www.googleapis.com/oauth2/v3/certs

    ->'Issuer':这将是发行者的 uri。例如:谷歌-https://accounts.google.com

    @Injectable()
    export class JwtStrategy extends PassportStrategy(Strategy) {
    
      constructor(
        @InjectRepository(UserRepository)
        private userRepository: UserRepository,
        private configService: ConfigService){
    
        super({
          secretOrKeyProvider: passportJwtSecret({
            cache: true,
            rateLimit: true,
            jwksRequestsPerMinute: 5,
            jwksUri: 'KEYS_URI',
          }),
          jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
          issuer: 'Issuer',
          algorithms: ['RS256'],
        });
      }
    
      async validate(payload: JwtPayloadInterface) {
    
        const { email } = payload;
        const user = await this.userRepository.findOne({ email });
    
        if(!user || !user.isActive) {
          throw new UnauthorizedException();
        }
    
        return user;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-11-03
      • 2019-03-28
      • 2021-11-25
      • 2021-03-02
      • 2018-11-08
      • 2019-09-13
      • 2019-12-28
      • 2023-03-25
      • 2018-11-28
      相关资源
      最近更新 更多