CDK中UserPoolIdentityProviderGoogle缺失email_verified映射属性的解决问询
解决Cognito CDK中映射Google身份提供商的
email_verified属性问题 通过AWS控制台配置Google作为Cognito身份提供商时,可直接映射email_verified属性实现登录后自动标记用户邮箱为已验证状态,但CDK的UserPoolIdentityProviderGoogle(L2构造)并未暴露该映射选项。以下是两种可行的实现方案:
方案一:使用L1构造直接配置
L1构造CfnUserPoolIdentityProvider是CloudFormation资源的直接封装,支持控制台中的所有配置项,包括email_verified的属性映射。
示例代码(TypeScript):
import { CfnUserPoolIdentityProvider } from 'aws-cdk-lib/aws-cognito'; // 假设已存在userPool实例 new CfnUserPoolIdentityProvider(this, 'GoogleIdp', { userPoolId: userPool.userPoolId, providerName: 'Google', providerType: 'Google', providerDetails: { client_id: '你的Google OAuth客户端ID', client_secret: '你的Google OAuth客户端密钥', authorize_scopes: 'openid email profile' }, attributeMapping: { email: 'email', emailVerified: 'email_verified' // 直接映射Google返回的email_verified到Cognito的emailVerified属性 } });
Google身份提供商会返回布尔类型的email_verified值,Cognito会自动接收并标记用户邮箱为已验证状态。
方案二:通过Post Authentication触发器实现
若偏好使用L2构造,可借助Cognito的Post Authentication Lambda触发器,手动更新用户的email_verified状态:
- 创建Lambda处理函数(Python示例):
import boto3 cognito_client = boto3.client('cognito-idp') def lambda_handler(event, context): # 校验用户是否通过Google身份提供商登录 identities = event['request']['userAttributes'].get('identities', []) if any(identity['providerName'] == 'Google' for identity in identities): idp_email_verified = event['request']['userAttributes'].get('email_verified') if idp_email_verified == 'true': # 更新Cognito用户的email_verified属性 cognito_client.admin_update_user_attributes( UserPoolId=event['userPoolId'], Username=event['userName'], UserAttributes=[ {'Name': 'email_verified', 'Value': 'true'} ] ) return event
- 在CDK中关联触发器到用户池:
import { UserPool } from 'aws-cdk-lib/aws-cognito'; import { Function, Runtime, Code, PolicyStatement } from 'aws-cdk-lib/aws-lambda'; const postAuthLambda = new Function(this, 'PostAuthLambda', { runtime: Runtime.PYTHON_3_11, handler: 'index.lambda_handler', code: Code.fromAsset('path/to/your/lambda/code') }); // 为Lambda添加更新用户属性的权限 postAuthLambda.addToRolePolicy(new PolicyStatement({ actions: ['cognito-idp:AdminUpdateUserAttributes'], resources: [userPool.userPoolArn] })); // 将触发器关联到用户池 const userPool = new UserPool(this, 'MyUserPool', { // 其他用户池配置项 lambdaTriggers: { postAuthentication: postAuthLambda } });
方案对比
- 方案一无需额外维护Lambda,直接利用CloudFormation原生配置,更简洁高效;
- 方案二更灵活,适合需要添加额外业务逻辑的场景,但需维护Lambda函数及相关权限。
内容的提问来源于stack exchange,提问作者aleksandralj
相关产品推荐
相关产品推荐

