此问题可能是由于API Gateway和Cognito之间的身份验证配置不正确所致。此外,您需要确保您使用的身份验证标头与API Gateway和Cognito身份验证配置中使用的相同。在SAM模板中,您需要配置AWS::Serverless::Api资源以便实现此目的。以下是如何配置资源以实现此目的的示例代码:
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: prod
Auth:
DefaultAuthorizer: MyCognitoAuthorizer
Authorizers:
MyCognitoAuthorizer:
UserPoolArn: !Sub 'arn:aws:cognito-idp:${AWS::Region}:${AWS::AccountId}:userpool/${MyUserPoolId}'
Identity:
Header: Authorization
Permission: Allow
在此示例代码中,我们使用AWS::Serverless::Api资源配置API Gateway。在Auth属性中,我们指定了默认的授权程序为MyCognitoAuthorizer,并创建了名为MyCognitoAuthorizer的其他授权程序。对于MyCognitoAuthorizer授权程序,我们指定了Cognito用户池的ARN,并使用身份验证标头Authorization。最后,我们指定允许访问API Gateway的权限。
如果您已经使用MyCognitoAuthorizer授权程序配置了API Gateway,但仍然遇到访问令牌被拒绝的问题,则可能需要检查您的Cognito用户池配置。确保您已正确配置用户池客户端设置和身份验证流。