AWS Amplify with GraphQL - 根据不同类型的用户定义身份验证规则

AWS Amplify with GraphQL - Defining authentication rules by different types of users

使用 Amplify、GraphQL、AppSync、Cognito、DynamoDB

有以下型号:

type Post
@model
{
  id: ID!
  content: String!
  author: String!
}

我希望我的规则启用以下情况:

  1. 只有管理员用户可以创建、更新和删除Post
  2. 一些 Post 只有高级用户才允许阅读的内容
  3. 部分 Post 所有登录用户都允许阅读
  4. 一些 Post 所有用户(也未通过身份验证)都允许阅读的

使用上述工具实现它的最佳方法是什么?

谢谢

根据您的问题,您不清楚如何定义“一些 Posts”以及如何区分它们。如果我正在设计这个,我的 Post 类型中至少会有一个字段来管理访问级别(例如:3 (Admin) > 2 (Premium) > 1 (Logged-in) > 0(未注册)),像这样;

type Post
@model
{
  id: ID!
  content: String!
  author: String!
  accessLevel: Int!
}

要在用户级别进行管理,我认为最好的办法是使用 Cognito 组进行管理(如 official documentation 中所述)并为每个组分配适当的权限。

您在 Cognito 中需要的东西:

  1. 一个用户,其中将包含您所有的注册用户。

  2. 高级会员的用户

  3. 一个用户 给你的管理员。

您在 AppSync 中需要的东西:

  1. 供管理员用户创建、更新和删除Post:

    type Mutation {
       createPost(id:ID!, content:String!, author:String!):Post!
       @aws_auth(cognito_groups: ["Admin"])
       updatePost(id:ID!, content:String!, author:String!):Post!
       @aws_auth(cognito_groups: ["Admin"])
       deletePost(id:ID!, content:String!, author:String!):Post!
       @aws_auth(cognito_groups: ["Admin"])
    }
    
  2. 对于某些 posts 仅对 premiumlogged-in未注册 用户阅读:

    type Query {
       getPost(id:ID!):Post!
       @aws_api_key @aws_cognito_user_pools
    }
    

    此外,您可以在解析器中使用 accessLevel 过滤出您希望 post 对高级用户、logged-in 或未注册用户可见的结果。

我使用了@Myz 的答案。 https://aws.amazon.com/blogs/mobile/graphql-security-appsync-amplify/ 完整解决方案:

  type Post
  @model
  @auth(
    rules: [
      { allow: owner }
      { allow: groups, groups: ["Admin"], operations: [create, update, delete] }
      { allow: groups, groupsField: "group", operations: [read] }
    ]
  ) {
  id: ID!
  content: String!
  author: String!
  group: [String] # or String for a single group
}