使用AWS Cognito、NestJS和Passport时Access Token验证失败排查
AWS Cognito 与 NestJS Access Token 验证失败的解决方法
在配置AWS Cognito与NestJS的Token验证功能时,参照网上示例实现了JwtStrategy,但始终无法完成Access Token的验证。
原问题代码
import { passportJwtSecret } from 'jwks-rsa'; import { ConfigService } from '@nestjs/config'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable } from '@nestjs/common'; @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor(private readonly configService: ConfigService) { super({ secretOrKeyProvider: passportJwtSecret({ cache: true, rateLimit: true, jwksRequestsPerMinute: 3, jwksUri: `https://cognito-idp.${configService.get( 'AWS_REGION' )}.amazonaws.com/${configService.get( 'AWS_COGNITO_USER_POOL_ID', )}/.well-known/jwks.json`, }), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), audience: configService.get('AWS_COGNITO_CLIENT_ID'), issuer: `https://cognito-idp.${configService.get( 'AWS_REGION', )}.amazonaws.com/${configService.get('AWS_COGNITO_USER_POOL_ID')}`, algorithms: ['RS256'], }); } async validate(payload: any) { return { userId: payload.sub, username: payload.username }; } }
问题原因
调试Passport的verify.js文件后发现:AWS Cognito签发的Access Token并未包含aud(受众)属性,但原配置中添加了audience校验项,导致验证逻辑不匹配,最终验证失败。
解决方案
移除JwtStrategy配置中的audience属性即可解决问题,修改后的代码如下:
@Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor(private readonly configService: ConfigService) { super({ secretOrKeyProvider: passportJwtSecret({ cache: true, rateLimit: true, jwksRequestsPerMinute: 3, jwksUri: `https://cognito-idp.${configService.get( 'AWS_REGION' )}.amazonaws.com/${configService.get( 'AWS_COGNITO_USER_POOL_ID', )}/.well-known/jwks.json`, }), jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), issuer: `https://cognito-idp.${configService.get( 'AWS_REGION', )}.amazonaws.com/${configService.get('AWS_COGNITO_USER_POOL_ID')}`, algorithms: ['RS256'], }); } async validate(payload: any) { return { userId: payload.sub, username: payload.username }; } }
内容的提问来源于stack exchange,提问作者vnedlechev
相关产品推荐
相关产品推荐

