AWS Amplify Auth规则不符合预期:OrgReq权限配置问题求助
问题解决思路
你的代码问题核心在于没有正确关联用户标识与权限规则,同时权限范围的定义不够明确,导致未过滤非自身的OrgReq对象。以下是具体修正方案:
核心问题分析
Amplify的allow: owner规则默认使用名为owner的字段作为用户标识,但你的模型里用的是userID,这条规则实际上没有生效;且未明确限制已认证用户的操作范围,导致读取请求没有过滤他人数据。
修正后的代码方案
方案一(明确Owner规则)
type OrgReq @model @auth(rules: [ # 已认证用户仅能创建归属自己的对象,强制userID匹配当前用户ID { allow: authenticated, operations: [create], condition: { userID: { eq: "$ctx.auth.uid" } } }, # 所有者(userID匹配当前用户)可读取、更新、删除自己的对象 { allow: owner, ownerField: "userID", operations: [read, update, delete] }, # admins组用户拥有全部操作权限 { allow: groups, groups: ["admins"], operations: [create, read, update, delete] } ]) { id: ID! name: String! street: String! zip: String! city: String! phoneNumber: String! state: String! userID: ID! @index # 添加索引优化权限过滤的查询性能 accepted: Boolean description: String }
方案二(简洁的条件限制)
直接通过authenticated规则加条件,统一限制已认证用户仅能操作自身对象,admins组不受限制:
type OrgReq @model @auth(rules: [ # 已认证用户所有操作均限制为自身对象 { allow: authenticated, operations: [create, read, update, delete], condition: { userID: { eq: "$ctx.auth.uid" } } }, # admins组用户拥有全部权限 { allow: groups, groups: ["admins"], operations: [create, read, update, delete] } ]) { id: ID! name: String! street: String! zip: String! city: String! phoneNumber: String! state: String! userID: ID! @index accepted: Boolean description: String }
关键说明
- 条件限制(condition):确保已认证用户创建、读取、更新、删除的对象必须是
userID等于当前用户ID的,从根源上过滤他人数据。 - ownerField指定:方案一中显式告诉Amplify使用
userID作为所有者字段,让allow: owner规则生效。 - @index索引:给
userID添加索引,大幅提升权限过滤时的查询效率,避免数据量变大后出现性能问题。
内容的提问来源于stack exchange,提问作者juri88
相关产品推荐
相关产品推荐

