如何使用AWS CDK配置Cognito身份池的访问控制属性实现自定义映射
解决方案
要完成Cognito身份池的访问控制属性配置,实现自定义主体键映射,你需要对现有代码做四处修改:
- 开启身份池Cognito提供商的服务端令牌校验,这是使用访问控制属性的前置要求
修改CfnIdentityPool的cognitoIdentityProviders配置:
const identityPool = new CfnIdentityPool(this, "IdentityPool", { allowUnauthenticatedIdentities: false, cognitoIdentityProviders: [{ clientId: userPoolClient.userPoolClientId, providerName: userPool.userPoolProviderName, serverSideTokenCheck: true, // 新增这行 }, ] });
- 修改认证角色的信任策略,添加
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"] // 修改这行,新增标签会话权限 ) })
- 配置用户池客户端的可读属性,确保自定义属性会被写入ID令牌
如果你还没配置用户池客户端的属性读取权限,需要在UserPoolClient初始化时添加对应配置,示例如下:
const userPoolClient = new UserPoolClient(this, "UserPoolClient", { userPool: userPool, // 其他原有配置保留 readAttributes: new ClientAttributes() .withStandardAttributes({/* 你需要的标准属性 */}) .withCustomAttributes("tenant_id") // 这里填你自定义属性的名称,去掉custom:前缀 })
- 修改身份池角色挂载配置,添加自定义属性映射规则并开启主体标签传递
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
相关产品推荐
相关产品推荐

