3

我正在将来自 Cognito 的 JWT 授权集成到我的 Nestjs 应用程序中,我遇到了一种鸡与蛋的情况。

如果为我的 Cognito 客户端生成 clientSecret,我将收到以下错误:

“无法验证客户端 {Client_Id} 的秘密哈希”

如果我在 Cognito 中创建新客户端时取消选中 clientScret generation,应用程序编译时会出现以下错误:

[ExceptionHandler] JwtStrategy 需要一个秘密或密钥 +0ms

我一直在遵循本指南来实现它:https ://brightinventions.pl/blog/using-cognito-with-nest-js/ ,但它并没有真正解决任何这些问题。

有人可以在这里提供一些指导吗?

4

2 回答 2

1

您分享的教程让后端处理用户注册、登录和注销。我想将访问令牌委托给 AWS Cognito。

对于请求受保护资源的用户,后端通过两种方式验证作为不记名令牌传递的访问令牌:

此外,此链接值得阅读https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html

如何验证 AWS Cognito 池生成的 jwt 令牌。

如果您不想访问其他用户信息,通过验证用户的访问令牌来验证用户就足够了。

如果要获取用户的其他信息(如邮箱和自定义属性),可以使用自己共享的版本,或者通过存储在 JWT 令牌中的用户子 id 获取用户信息。

谢谢,愉快的编码。希望这可以帮助你。

于 2020-12-24T06:59:27.910 回答
0
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, Logger, UnauthorizedException } from '@nestjs/common';
import { passportJwtSecret } from 'jwks-rsa';


@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: https://cognito-idp.{region}.amazonaws.com/{userPoolId}/.well-known/jwks.json
      }),

      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: 'client id',
      issuer: https://cognito-idp.<region>.amazonaws.com/<userpoolID>.
      algorithms: ['RS256'],
      
    });
  }

  async validate(payload: any) {
    console.debug('JWT VALIDATION')
    return !!payload.sub;
  }
}

于 2021-11-06T17:31:08.773 回答