在使用 AWS Cognito 的 Google 登录时,需要注意同步 Google 用户信息到用户池中的映射属性时可能会出现覆盖的情况。为避免这种情况,可以在 Google 登录授权后,使用 AWS SDK 更新用户池中的用户信息,而不是直接使用 Google 返回的用户信息。
具体的代码实现方法需要使用 AWS SDK 中的 CognitoIdentityServiceProvider 类,示例代码如下:
import AWS from 'aws-sdk';
const cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider();
// Google 登录授权后的回调函数
const handleGoogleLogin = async (googleUser) => {
// 从 Google 返回的用户信息中获取用户唯一的 sub id
const sub = googleUser.getBasicProfile().getId();
// 获取用户池中的用户信息
const params = {
UserPoolId: 'USER_POOL_ID',
Filter: `sub = "${sub}"`,
};
const { Users } = await cognitoIdentityServiceProvider.listUsers(params).promise();
const [ user ] = Users;
// 更新用户池中的映射属性
const updateUserParams = {
UserPoolId: 'USER_POOL_ID',
Username: user.Username,
UserAttributes: [
{
Name: 'email',
Value: googleUser.getBasicProfile().getEmail(),
},
// 更多映射属性
],
};
await cognitoIdentityServiceProvider.adminUpdateUserAttributes(updateUserParams).promise();
};
通过使用上面的示例代码,可以避免 AWS Cognito 的 Google 登录覆盖用户池中映射属性的值的问题。同时,也可以根据实际需求,更新更多的映射属性。