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

如何在Cognito中让联邦用户关联本地用户后自动设email_verified为True

解决Cognito关联联邦用户后email_verified被重置为False的问题

核心原因

在Pre sign-up触发器中执行用户关联和属性修改时,Cognito后续的身份关联流程会用联邦身份提供商返回的属性(通常email_verified为False)覆盖本地用户的原有属性,导致之前的修改失效。

可行解决思路

1. 使用Post Authentication触发器修改属性

将属性更新逻辑移至Post Authentication触发器(用户完成认证和关联后触发),此时修改的属性不会被后续流程覆盖:

  • 编写Lambda代码调用admin_update_user_attributes强制设置email_verified为True:
    import boto3
    
    cognito_client = boto3.client('cognito-idp')
    
    def lambda_handler(event, context):
        user_sub = event['request']['userAttributes']['sub']
        pool_id = event['userPoolId']
        
        cognito_client.admin_update_user_attributes(
            UserPoolId=pool_id,
            Username=user_sub,
            UserAttributes=[
                {'Name': 'email_verified', 'Value': 'True'}
            ]
        )
        return event
    
  • 给Lambda函数授予cognito-idp:AdminUpdateUserAttributes权限。

2. 配置SAML提供商传递email_verified属性

让Azure AD在SAML断言中返回email_verified为true,Cognito会直接继承该属性:

  • 在Azure AD的应用程序声明映射中,添加自定义声明:
    • 声明名称:https://aws.amazon.com/cognito/claims/email_verified
    • 值:设置为true(可直接硬编码,或映射到Azure AD中用户的邮箱验证状态)
  • 在Cognito用户池的SAML身份提供商设置中,确保email_verified属性被正确映射到用户池的对应属性。

3. 调整Pre sign-up触发器的执行顺序

如果必须使用Pre sign-up触发器,需确保在调用admin_link_provider_for_user之后立即执行属性更新,并且显式指定本地用户的属性:

import boto3

cognito_client = boto3.client('cognito-idp')

def lambda_handler(event, context):
    # 先执行用户关联逻辑
    cognito_client.admin_link_provider_for_user(
        UserPoolId=event['userPoolId'],
        DestinationUser={
            'ProviderName': 'Cognito',
            'ProviderAttributeValue': '本地用户的用户名或邮箱'
        },
        SourceUser={
            'ProviderName': 'AzureAD',
            'ProviderAttributeValue': event['request']['userAttributes']['email']
        }
    )
    
    # 关联后立即更新本地用户的email_verified属性
    cognito_client.admin_update_user_attributes(
        UserPoolId=event['userPoolId'],
        Username='本地用户的用户名',
        UserAttributes=[
            {'Name': 'email_verified', 'Value': 'True'}
        ]
    )
    return event

注意:此方法仍可能被Cognito后续流程覆盖,优先推荐前两种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 16:10:14