You need to enable JavaScript to run this app. Flutter使用Amplify API发Post请求IAM授权返回403错误如何解决
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 15:06:02