You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Amplify多租户场景下如何组合owner与group类型@auth授权规则?

AWS Amplify多租户@auth规则组合方案

要实现租户匹配+用户组权限的组合逻辑,核心是利用Amplify @auth规则的condition表达式——因为默认的多规则是逻辑或关系,只有在单个规则内通过条件才能实现“同时满足多个要求”的逻辑。以下分两种场景给出具体实现:

场景1:仅指定组用户且租户匹配时允许操作

要求:Admin组用户匹配租户时可执行所有操作,Member组用户匹配租户时仅能读数据。

type Customer @model
  @key(fields: ["company", "id"])
  @auth(rules: [
    # Admin组:匹配租户字段,允许所有操作
    { 
      allow: groups, 
      groups: ["Admin"],
      # 兼容创建/读写删操作的租户匹配逻辑
      condition: { 
        or: [
          { eq: ["$ctx.identity.custom.company", "$ctx.args.input.company"] },
          { eq: ["$ctx.identity.custom.company", "$ctx.source.company"] }
        ]
      }
    },
    # Member组:匹配租户字段,仅允许读操作
    { 
      allow: groups, 
      groups: ["Member"], 
      operations: [read],
      condition: { eq: ["$ctx.identity.custom.company", "$ctx.source.company"] }
    }
  ])
{
  company: ID!
  id: ID!
  # 其他业务字段
}

场景2:所有租户匹配用户均可访问,但Member组仅能读

要求:所有custom:company匹配数据company字段的用户都能访问,但Member组用户仅允许读操作,Admin组用户允许所有操作。

type Customer @model
  @key(fields: ["company", "id"])
  @auth(rules: [
    # Admin组:匹配租户,允许所有操作
    { 
      allow: groups, 
      groups: ["Admin"],
      condition: { 
        or: [
          { eq: ["$ctx.identity.custom.company", "$ctx.args.input.company"] },
          { eq: ["$ctx.identity.custom.company", "$ctx.source.company"] }
        ]
      }
    },
    # 租户匹配用户:Member组仅允许读,其他用户允许所有操作
    { 
      allow: owner, 
      ownerField: "company", 
      identityClaim: "custom:company",
      condition: { 
        or: [
          # 不属于Member组,允许所有操作
          { not: { in: ["Member", "$ctx.identity.groups"] } },
          # 属于Member组,仅允许读操作
          { eq: ["$ctx.operation", "read"] }
        ]
      }
    }
  ])
{
  company: ID!
  id: ID!
  # 其他业务字段
}

关键说明

  1. 规则逻辑:Amplify @auth规则是逻辑或关系,只要满足任意一条规则就会授权,因此必须在单个规则内用condition组合“租户匹配”和“用户组”两个条件。
  2. 上下文变量:
    • $ctx.identity.custom.company:获取当前用户的Cognito自定义属性值
    • $ctx.identity.groups:获取当前用户所属的Cognito组列表
    • $ctx.source.company:操作时的数据对象租户字段(适用于read/update/delete)
    • $ctx.args.input.company:创建时的输入租户字段(适用于create)
  3. 操作区分:create操作没有$ctx.source,必须用$ctx.args.input来匹配租户ID;其他操作可以直接用$ctx.source。

内容的提问来源于stack exchange,提问作者mdwt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 18:35:36