使用AWS JS SDK v3的AdminUpdateUserAttributesCommand无法更新Cognito用户邮箱
AWS Cognito 用户邮箱属性更新失败问题
问题描述
我使用AWS JavaScript SDK v3的AdminUpdateUserAttributesCommand更新Cognito用户属性时,given_name、family_name等字段能正常更新,但邮箱字段始终无法修改——调用返回200状态码,没有任何错误抛出。
我的用户池配置为「使用邮箱作为登录别名」,但在AWS控制台直接修改该用户邮箱是可行的,说明邮箱字段本身支持修改。想知道是不是登录别名的设置导致了SDK调用无法更新邮箱,以及对应的解决办法。
用户池配置
Alias attributes used to sign in: Email
相关代码
import { APIGatewayEvent, APIGatewayProxyResult } from "aws-lambda"; import { AdminUpdateUserAttributesCommand, AdminUpdateUserAttributesCommandInput, CognitoIdentityProviderClient, } from "@aws-sdk/client-cognito-identity-provider"; export const index = new CognitoIdentityProviderClient({ region: process.env.AWS_REGION, }); const userPool = process.env.AUTH_QQQ_USERPOOLID || "us-east-2_QQQ"; export const handler = async ( event: APIGatewayEvent ): Promise<APIGatewayProxyResult> => { let result: any = ""; if (event?.body) { const request = JSON.parse(event.body); console.log("~~~ request: ", request); const userName = "QQQ-f263-4a3e-85be-QQQ"; // 临时硬编码排除参数错误 const attributes = [ { Name: "email", // given_name、family_name可正常更新 Value: "user1@gmail.com", // 临时硬编码 }, ]; console.log("~~~ userPool: ", userPool); console.log("~~~ userName: ", userName); console.log("~~~ attributes: ", attributes); const command = new AdminUpdateUserAttributesCommand({ UserPoolId: userPool, Username: userName, UserAttributes: attributes, } as AdminUpdateUserAttributesCommandInput); const response = await index.send(command); console.log("~~~ response: " + JSON.stringify(response)); result = response; } else { console.error("userUpdate without body. event: " + JSON.stringify(event)); } return { statusCode: 200, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Headers": "*", }, body: result.toString(), }; };
调用响应
{ "$metadata": { "httpStatusCode": 200, "requestId": "QQQ-70f4-4896-a48d-0ac55872f4b2", "attempts": 1, "totalRetryDelay": 0 } }
解决方案
原因分析
当邮箱被设置为用户池的登录别名时,Cognito对email属性的更新有特殊要求:必须同时指定email_verified属性,否则即使调用返回200,邮箱更新也会被静默忽略。这是因为作为登录别名的邮箱涉及用户身份验证逻辑,Cognito需要明确知道新邮箱的验证状态。
解决步骤
修改属性数组,添加email_verified字段即可:
const attributes = [ { Name: "email", Value: "user1@gmail.com", }, { Name: "email_verified", Value: "false", // 根据业务需求设置:false表示需要用户验证新邮箱,true表示管理员直接验证(需用户池允许) }, ];
注意事项
- 如果将
email_verified设为true,要确保该邮箱未被用户池内其他用户使用,且你的用户池配置允许管理员直接验证邮箱(无需用户确认)。 - 修改后重新调用接口,即可在Cognito控制台看到用户邮箱已更新。
内容的提问来源于stack exchange,提问作者Scott Norland
相关产品推荐
相关产品推荐

