Amplify GraphQL V1转V2后未认证用户IAM访问401错误求助
解决Amplify GraphQL Transformer V2中未认证用户IAM访问401问题
Transformer V2对权限规则的处理逻辑和V1存在差异,导致未认证用户的IAM访问权限配置需要调整,以下是针对性的解决步骤:
1. 修正Schema中的@auth规则
V2中allow: public默认对应API Key认证,未认证用户通过IAM访问需要显式指定allow: unauthenticated并搭配provider: iam,示例Schema如下:
type Book @model @auth(rules: [ { allow: admin, operations: [create, update, delete] }, { allow: authenticated, operations: [read] }, { allow: unauthenticated, provider: iam, operations: [read] } ]) { id: ID! title: String! }
确保每个规则的operations覆盖对应的读写操作,避免权限遗漏。
2. 确认Auth资源启用未认证身份
检查Amplify Auth配置,确保允许未认证用户访问:
- 若使用TS配置文件(
amplify/auth/resource.ts):
export const auth = defineAuth({ loginWith: { email: true, }, allowUnauthenticatedIdentities: true, // 必须设为true });
- 若使用旧版JSON配置(
amplify/backend/auth/<auth-name>/parameters.json):
{ "allowUnauthenticatedIdentities": true }
3. 验证未认证IAM角色权限
登录AWS控制台,找到项目对应的未认证角色(命名格式:amplify-<项目名>-<环境>-<随机串>-unauthRole),检查附加的IAM策略是否包含GraphQL API的读取权限:
{ "Effect": "Allow", "Action": ["appsync:GraphQL"], "Resource": [ "arn:aws:appsync:<区域>:<账号ID>:apis/<API ID>/types/Book/fields/*", "arn:aws:appsync:<区域>:<账号ID>:apis/<API ID>/types/Query/fields/listBooks", "arn:aws:appsync:<区域>:<账号ID>:apis/<API ID>/types/Query/fields/getBook" ] }
若策略缺失,可重新执行amplify push让Transformer自动生成,或手动添加上述权限语句。
4. 客户端显式指定IAM认证模式
调用GraphQL API时,需明确指定authMode: 'IAM',避免使用默认的认证模式导致权限不匹配:
import { API, graphqlOperation } from 'aws-amplify'; import { listBooks } from './graphql/queries'; const fetchBooks = async () => { try { const response = await API.graphql({ query: listBooks, authMode: 'IAM' }); console.log('Books:', response.data.listBooks.items); } catch (error) { console.error('Fetch error:', error); } };
完成以上步骤后,重新执行amplify push部署更新,未认证用户即可通过IAM正常读取图书数据。
内容的提问来源于stack exchange,提问作者chris-j
相关产品推荐
相关产品推荐

