如何防止更新 AWS Amplify GraphQL API 的ownerField?

rob*_*ton 2 amazon-web-services amplifyjs graphql aws-amplify aws-amplify-sdk-js

我使用 AWS 的 Amplify 创建了一个 GraphQL API。在架构中,我有一个评论模型,如下所示:

type Comment
  @auth(rules: [{ allow: owner }, { allow: private, operations: [read] }, { allow: public, operations: [read] }])
  @model
  @key(name: "byAuthor", fields: ["authorID"])
  @key(name: "byPost", fields: ["postID"]) {
  content: String!
  createdAt: AWSDateTime!
  id: ID!
  owner: String
  postID: ID!
  updatedAt: AWSDateTime!
}
Run Code Online (Sandbox Code Playgroud)

这为所有者提供了创建、读取、更新和删除的权限,并将未经身份验证/经过身份验证的非所有者用户限制为只读。这按预期工作;然而,所有者可以更新ownerField 的值,本质上是将评论归因于另一个用户......这是一个禁忌。为了防止这种情况,我尝试使用字段级权限(见下文);然而,这似乎并没有阻止更新。

...
owner: String @auth(rules: [{ allow: owner, operations: [ create ]}])
...
Run Code Online (Sandbox Code Playgroud)

我有什么遗漏的吗?非常感谢任何帮助——谢谢!

小智 6

你们非常接近。使用字段级@auth指令,您希望显式授予所有者执行 和 的能力createread并显式拒绝世界执行 和update的能力delete。它可能看起来像:

type Todo
    @model
    @auth(rules: [{ allow: owner, ownerField: "author" }]) {
    id: ID!
    name: String!
    author: String
        @auth(
            rules: [
                { allow: groups, groups: ["FORBIDDEN"], operations: [update, delete] }
                { allow: owner, ownerField: "author", operations: [create, read] }
            ]
        )
}
Run Code Online (Sandbox Code Playgroud)

这里,“FORBIDDEN”组是不存在的组。它的名称可以是任何名称,只要您不打算将来实际创建一个使用该名称的组即可。由于任何用户都不会拥有“FORBIDDEN”组声明,因此该字段上的任何/所有update操作delete都将失败。