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

如何在Python CDK中配置身份池的preferred_role claim角色识别方式

在Python CDK中配置身份池使用Preferred Role Claim

实现步骤与代码示例

要在Python CDK中配置身份池使用「preferred_role claim」选项,需要通过**L1构造CfnIdentityPoolRoleAttachment**来配置角色映射,因为L2构造暂时未直接暴露该配置项。核心是将角色映射的type字段设置为"PreferredRole"。

代码示例

from aws_cdk import (
    aws_cognito as cognito,
    aws_iam as iam,
    core as cdk
)

class MyStack(cdk.Stack):
    def __init__(self, scope: cdk.App, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # 引用已有的Cognito用户池与客户端(也可新建)
        user_pool = cognito.UserPool.from_user_pool_id(
            self, "ExistingUserPool",
            user_pool_id="your-user-pool-id"
        )
        user_pool_client = cognito.UserPoolClient.from_user_pool_client_id(
            self, "ExistingUserPoolClient",
            user_pool_client_id="your-client-id"
        )

        # 创建身份池
        identity_pool = cognito.CfnIdentityPool(
            self, "MyIdentityPool",
            allow_unauthenticated_identities=False,
            cognito_identity_providers=[{
                "clientId": user_pool_client.user_pool_client_id,
                "providerName": f"cognito-idp.{cdk.Aws.REGION}.amazonaws.com/{user_pool.user_pool_id}"
            }]
        )

        # 配置角色映射为Preferred Role Claim
        cognito.CfnIdentityPoolRoleAttachment(
            self, "MyIdentityPoolRoleMapping",
            identity_pool_id=identity_pool.ref,
            role_mappings={
                "CognitoPreferredRoleMapping": {
                    "identityProvider": f"cognito-idp.{cdk.Aws.REGION}.amazonaws.com/{user_pool.user_pool_id}:{user_pool_client.user_pool_client_id}",
                    "type": "PreferredRole",
                    # 可选:当用户无preferred_role claim时使用的默认角色
                    "defaultRoleArn": iam.Role.from_role_arn(
                        self, "DefaultAuthRole",
                        role_arn="arn:aws:iam::your-account-id:role/your-default-auth-role"
                    ).role_arn
                }
            }
        )

关键配置说明

  • type: "PreferredRole":对应控制台的第三个选项,身份池会读取Cognito用户JWT中的preferred_role claim来分配IAM角色。
  • identityProvider:必须填写完整的Cognito身份提供商标识符,格式为cognito-idp.<区域>.amazonaws.com/<用户池ID>:<客户端ID>。
  • defaultRoleArn(可选):当用户的JWT中没有preferred_role claim时,会使用该默认角色。

官方文档位置

  • AWS CDK Python 文档:查看aws_cognito.CfnIdentityPoolRoleAttachment类的role_mappings属性说明,其中明确了type字段支持PreferredRole值。
  • Amazon Cognito 开发者指南:在「身份池角色映射」章节中,有关于使用preferred_role claim配置角色分配的详细说明。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 13:07:11