如何从Lambda函数调用使用AWS_IAM授权的AWS AppSync API
问题排查与解决方案
1. 修正IAM角色的资源配置
你当前的IAM策略中Resource配置仅指定了GraphQL API根ARN,不符合AppSync的权限校验规则,必须精确到具体的Mutation字段:
Policies: - PolicyName: ${self:provider.stage}-UpdateUserMutationLambdaPolicy PolicyDocument: Version: "2012-10-17" Statement: - Effect: Allow Action: - appsync:GraphQL Resource: # 替换为你实际的区域、账号ID、AppSync API ID - arn:aws:appsync:<region>:<account-id>:apis/<api-id>/types/Mutation/fields/updateUser
如果需要放开所有Mutation权限可改为arn:aws:appsync:<region>:<account-id>:apis/<api-id>/types/Mutation/*,建议遵循最小权限原则配置到具体字段。
2. 修正Lambda签名逻辑,补全Session Token
Lambda运行时自动提供的是临时安全凭证,必须同时传入aws_session_token才能完成AWS4签名,你当前代码漏传该参数,且不应该硬编码访问密钥:
正确代码示例:
import boto3 import requests from requests_aws4auth import AWS4Auth # 从Lambda执行环境自动获取临时凭证,无需硬编码 credentials = boto3.Session().get_credentials() auth = AWS4Auth( credentials.access_key, credentials.secret_key, <region>, 'appsync', session_token=credentials.token # 必须传入session token,否则会报Session Token无效 ) query = """ mutation UpdateUser($user_id: String!) { updateUser(user_id: $user_id) } """ variables = {"user_id": "你的用户ID"} response = requests.post( url=APPSYNC_API_ENDPOINT_URL, auth=auth, json={'query': query, "variables": variables} )
依赖包需要提前打包到Lambda层或部署包:requests、requests-aws4auth、boto3。
3. 确认AppSync授权模式配置
检查serverless-appsync-plugin配置中已开启IAM作为额外授权器:
appSync: name: your-api-name authenticationType: AWS_COGNITO_USER_POOLS userPoolConfig: # 你的Cognito配置 additionalAuthenticationProviders: - authenticationType: AWS_IAM # 必须存在该配置,否则IAM授权不生效
4. 其他排查点
- 确认Mutation定义的
@aws_iam指令已正确生效,部署后可在AppSync控制台的Schema页面查看该Mutation的授权配置 - 不要在请求中手动添加其他
Authorization头,避免和AWS4Auth自动生成的签名头冲突 - 检查Lambda执行角色是否有多余的权限边界限制,阻断了AppSync调用权限
内容的提问来源于stack exchange,提问作者Akshat Kumar Gupta
相关产品推荐
相关产品推荐

