下面是一个使用API网关和自定义Lambda授权者验证传递的头部值是否存在于Cognito用户池群组中的示例代码:
import json
import boto3
def lambda_handler(event, context):
# 获取传递的头部值
username = event['headers'].get('Username')
# 验证用户名是否存在于Cognito用户池群组中
client = boto3.client('cognito-idp')
response = client.admin_list_groups_for_user(
UserPoolId='YOUR_USER_POOL_ID',
Username=username
)
# 检查用户是否在群组中
groups = response['Groups']
if len(groups) == 0:
return {
'statusCode': 403,
'body': 'User is not authorized to access this resource'
}
# 用户已经验证,可以继续处理请求
return {
'statusCode': 200,
'body': 'User is authorized'
}
在AWS控制台中创建一个Lambda函数,并将上述代码复制到函数中。
在API网关中创建一个自定义Lambda授权者:
{
"headers": {
"Username": "$input.params('username')"
}
}
现在,当客户端通过API网关发送请求时,API网关将使用自定义Lambda授权者验证传递的头部值是否存在于Cognito用户池群组中。只有当用户在群组中时,API网关才会允许请求通过。否则,API网关将返回一个403状态码和相应的错误消息。