You need to enable JavaScript to run this app. 如何使用AWS CDK配置Cognito身份池的访问控制属性实现自定义映射
优惠活动
大模型
产品
解决方案
定价
更多

如何使用AWS CDK配置Cognito身份池的访问控制属性实现自定义映射

解决方案

要完成Cognito身份池的访问控制属性配置,实现自定义主体键映射,你需要对现有代码做四处修改:

  1. 开启身份池Cognito提供商的服务端令牌校验,这是使用访问控制属性的前置要求
    修改CfnIdentityPool的cognitoIdentityProviders配置:
const identityPool = new CfnIdentityPool(this, "IdentityPool", {
  allowUnauthenticatedIdentities: false,
  cognitoIdentityProviders: [{
    clientId: userPoolClient.userPoolClientId,
    providerName: userPool.userPoolProviderName,
    serverSideTokenCheck: true, // 新增这行
  }, ]
});
  1. 修改认证角色的信任策略,添加sts:TagSession权限,允许传递主体标签
const authenticatedRole = new Role(this, "AuthenticatedRole", {
  assumedBy: new FederatedPrincipal(
    'cognito-identity.amazonaws.com', {
      "StringEquals": {
        "cognito-identity.amazonaws.com:aud": identityPool.ref
      },
      "ForAnyValue:StringLike": {
        "cognito-identity.amazonaws.com:amr": "authenticated"
      },
    }, 
    ["sts:AssumeRoleWithWebIdentity", "sts:TagSession"] // 修改这行,新增标签会话权限
  )
})
  1. 配置用户池客户端的可读属性,确保自定义属性会被写入ID令牌
    如果你还没配置用户池客户端的属性读取权限,需要在UserPoolClient初始化时添加对应配置,示例如下:
const userPoolClient = new UserPoolClient(this, "UserPoolClient", {
  userPool: userPool,
  // 其他原有配置保留
  readAttributes: new ClientAttributes()
    .withStandardAttributes({/* 你需要的标准属性 */})
    .withCustomAttributes("tenant_id") // 这里填你自定义属性的名称,去掉custom:前缀
})
  1. 修改身份池角色挂载配置,添加自定义属性映射规则并开启主体标签传递
new CfnIdentityPoolRoleAttachment(this, 'IdentityPoolRoleAttachment', {
  identityPoolId: identityPool.ref,
  roles: {
    "authenticated": authenticatedRole.roleArn,
    "unauthenticated": unauthenticatedRole.roleArn
  },
  roleMappings: {
    mapping: {
      type: "Token",
      ambiguousRoleResolution: "Deny",
      identityProvider: `cognito-idp.${Stack.of(this).region}.amazonaws.com/${userPool.userPoolId}:${userPoolClient.userPoolClientId}`,
      addPrincipalTags: true, // 新增这行,开启主体标签传递
      // 新增以下规则配置,映射你需要的自定义属性
      rulesConfiguration: {
        rules: [
          {
            claim: "custom:tenant_id", // 这里填ID令牌中你的自定义属性完整名称,带custom:前缀
            matchType: "Equals",
            value: "*",
            roleArn: authenticatedRole.roleArn
          }
          // 有多个要映射的属性可以在这里新增多条规则
        ]
      }
    }
  }
})

部署后你就能在身份池的访问控制属性页看到你配置的自定义主体键映射。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 11:45:03