Flutter使用Amplify API发Post请求IAM授权返回403错误如何解决
问题解决指南
1. 必备依赖配置检查
IAM授权模式要求你同时集成并初始化Amplify Auth模块,用于自动生成API请求的IAM签名,你需要确认三点:
- 项目
pubspec.yaml中已同时添加amplify_api和amplify_auth_cognito依赖 - Amplify初始化代码中同时注册两个插件,示例如下:
import 'package:amplify_api/amplify_api.dart'; import 'package:amplify_auth_cognito/amplify_auth_cognito.dart'; import 'package:amplify_flutter/amplify_flutter.dart'; import 'amplifyconfiguration.dart'; Future<void> _configureAmplify() async { final auth = AmplifyAuthCognito(); final api = AmplifyAPI(); await Amplify.addPlugins([auth, api]); try { await Amplify.configure(amplifyconfig); } on AmplifyAlreadyConfiguredException { safePrint("Amplify already configured"); } }
- 确认
amplifyconfiguration.json文件中对应API的authorizationType字段值为AWS_IAM
2. IAM角色权限配置
你需要为Cognito对应的身份池角色(分为已认证用户角色和未认证匿名用户角色)添加API Gateway的调用权限,权限策略示例如下:
{ "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "execute-api:Invoke" ], "Resource": [ "arn:aws:execute-api:<区域>:<账号ID>:<API ID>/*/*/*" ] } ] }
如果你需要开启匿名访问,需要先在Amplify Auth配置中开启未认证用户访问功能,执行amplify update auth按提示选择开启未认证用户访问后,执行amplify push生效即可。
3. 代码优化
你的现有请求逻辑无需额外添加签名头,Amplify会自动为IAM授权的API请求添加签名,可优化JSON构造逻辑避免转义错误:
Future<List<ChapterData>> getChapters(String subjectID) async { try { // 用jsonEncode替代手动拼接字符串,避免特殊字符转义错误 final postBody = jsonEncode({"subject_id": subjectID}); RestOptions options = RestOptions( path: "/getChapterList", body: Uint8List.fromList(postBody.codeUnits), apiName: "getChapterList"); RestOperation restOperation = Amplify.API.post(restOptions: options); RestResponse response = await restOperation.response; final respJson = json.decode(String.fromCharCodes(response.data)); return ChapterData.fromJson(respJson); } on ApiException catch (e) { print('post call failed: $e'); rethrow; } }
4. 排查方向
- 确认你调用的
apiName和路径与Amplify配置文件中定义的完全一致,无拼写错误 - 排查API Gateway的日志,确认403是权限校验失败返回,而非后端Lambda执行报错返回
- 检查Lambda执行角色是否具备DynamoDB的对应读写权限
内容的提问来源于stack exchange,提问作者Siva
相关产品推荐
相关产品推荐

