如何为Amplify DataStore多对多关联添加权限控制?
如何在Amplify DataStore中为多对多关联的Post资源添加权限控制?
我明白你现在卡在哪了——官方文档里确实没怎么提带权限控制的多对多关联示例,尤其是要限制只有PostEditor能访问Post的场景。结合你给出的模型,我会用Cognito+Amplify自定义权限规则来实现这个需求,下面是一步步的做法:
1. 修改GraphQL模型,添加权限规则
首先调整你的模型,给每个类型加上对应的@auth规则,核心是让Post的读取权限只开放给它的编辑器:
# 用户类型:绑定Cognito的sub,用户只能访问自己的记录 type User @model @auth(rules: [{ allow: owner, ownerField: "id", identityClaim: "sub" }]) { id: ID! # 这里的id要对应Cognito用户的sub字段 username: String! posts: [PostEditor] @connection(keyName: "byEditor", fields: ["id"]) } # 文章类型:仅允许该文章的编辑器读取,可选允许创建者管理 type Post @model @auth(rules: [ { allow: private, operations: [read], # 条件:当前用户是该文章的编辑器(通过PostEditor关联判断) condition: { exists: { operator: "in", operand: "id", inQuery: { query: "PostEditor", field: "postID", filter: { editorID: { eq: "${ctx.identity.sub}" } } } } } }, { allow: owner, operations: [create, update, delete] } # 可选:让文章创建者能修改/删除文章 ]) { id: ID! title: String! editors: [PostEditor] @connection(keyName: "byPost", fields: ["id"]) } # 中间关联表:仅允许编辑器和文章创建者操作 type PostEditor @model(queries: null) @key(name: "byPost", fields: ["postID", "editorID"]) @key(name: "byEditor", fields: ["editorID", "postID"]) @auth(rules: [ { allow: owner, ownerField: "editorID", identityClaim: "sub" }, # 编辑器能访问自己的关联记录 { allow: owner, ownerField: "postID", identityClaim: "sub" } # 文章创建者能管理编辑器列表 ]) { id: ID! postID: ID! editorID: ID! post: Post! @connection(fields: ["postID"]) editor: User! @connection(fields: ["editorID"]) }
规则说明:
- Post的读取权限:通过
inQuery查询PostEditor表,检查当前用户的Cognito sub是否存在于该文章的编辑器列表中,只有符合条件的用户才能读取文章。 - User类型权限:确保用户只能查看自己的用户信息,避免敏感数据泄露。
- PostEditor权限:限制只有关联的编辑器和文章创建者能操作这个中间表,防止无关用户随意添加/删除编辑器。
2. 部署模型并同步DataStore
修改完模型后,执行以下命令更新你的Amplify API:
amplify push amplify codegen models
这会把新的权限规则部署到AppSync,同时更新本地DataStore的模型文件,确保本地同步逻辑遵守云端的权限规则。
3. 验证权限是否生效
你可以通过以下步骤测试:
- 用用户A的身份创建一篇Post。
- 创建PostEditor关联,把用户B的sub(Cognito用户的唯一标识)关联到这篇Post。
- 切换到用户B的身份,DataStore应该能正常加载这篇Post。
- 切换到用户C的身份,DataStore加载Post时会返回空列表,因为用户C不在该Post的编辑器列表里。
替代方案(如果不想用Cognito)
如果你不想用Cognito,也可以用Amplify的自定义认证方案,比如基于JWT的第三方认证。核心思路还是在@auth规则中通过identityClaim获取用户的唯一标识,然后用同样的条件判断逻辑来限制Post的读取权限。
内容的提问来源于stack exchange,提问作者callmetwan
相关产品推荐
相关产品推荐

