问题的解决需要在API Gateway的设置中进行配置。具体来说,需要启用“AWS_IAM”身份验证类型,并将API Gateway上的Cognito用户池与相应的作者器ARN(Amazon资源名称)关联起来。 以下是一个Python的代码示例,用于在API Gateway中启用身份验证类型和关联Cognito用户池:
import boto3
import json
client = boto3.client('apigateway')
rest_api_id = 'your_rest_api_id'
resource_id = 'your_resource_id'
method = 'your_http_method'
# Enable AWS_IAM authorization
client.update_method(
restApiId=rest_api_id,
resourceId=resource_id,
httpMethod=method,
patchOperations=[
{
'op': 'add',
'path': '/authorizationType',
'value': 'AWS_IAM'
}
]
)
# Associate Cognito User Pool with Authorizer ARN
authorizer_arn = 'your_authorizer_arn'
cognito_user_pool_id = 'your_cognito_user_pool_id'
client.create_authorizer(
restApiId=rest_api_id,
name='cognito-authorizer',
type='COGNITO_USER_POOLS',
identitySource='method.request.header.Authorization',
providerArns=[authorizer_arn],
authType='cognito',
authorizerUri=f'arn:aws:apigateway:{aws_region}:lambda:path/2015-03-31/functions/{your_lambda_function_ARN}/invocations',
authorizerResultTtlInSeconds=300,
authorizerCredentials='arn:aws:iam::{your_account_id}:role/{your_cognito_authorization_role}',
identityValidationExpression='^[A-Za-z0-9-_=.]+(\.[A-Za-z0-9-_=.]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,})$',
providerARNs=[authorizer_arn],
cognitoUserPool={
"poolId": cognito_user_pool_id,
"awsRegion": aws_region
}
)
通过这个代码,你可以把Cognito授权信息转发到你的Lambda函数中。