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

如何将社交登录获取的凭证存入AWS Cognito用户池?

解决方案

要将社交媒体登录的凭证(Token、邮箱ID)存入AWS Cognito用户池,你需要结合Cognito用户池的联合身份认证流程,在第三方登录成功后同步用户信息到用户池。以下是具体步骤和代码调整:

前提配置

确保你的AWS Cognito用户池已完成以下配置:

  • 添加对应社交媒体平台(比如你代码中的Google)作为身份提供商,填入平台OAuth客户端ID、密钥,并设置正确的回调URL
  • 用户池客户端启用了联合身份认证,允许该社交媒体平台的登录请求

代码调整与实现

你当前的代码仅完成了身份池的联合登录,要同步数据到用户池,需在登录成功后获取Cognito用户实例,并更新用户属性:

AWSMobileClient.getInstance().initialize(this, new Callback<UserStateDetails>() {
    @Override
    public void onResult(UserStateDetails userStateDetails) {
        Log.i("INIT", String.valueOf(userStateDetails.getUserState()));
        AWSMobileClient.getInstance().federatedSignIn(IdentityProvider.GOOGLE.toString(), account.getIdToken(), new Callback<UserStateDetails>() {
            @Override
            public void onResult(final UserStateDetails userStateDetails) {
                Log.i(TAG, "mobileClient Google login result: " + userStateDetails.getUserState().toString());
                
                // 登录成功后,获取Cognito用户池的用户实例
                CognitoUser cognitoUser = AWSMobileClient.getInstance().getCognitoUser();
                if (cognitoUser != null) {
                    // 准备要存入用户池的属性:邮箱ID、第三方登录Token
                    List<CognitoUserAttribute> attributes = new ArrayList<>();
                    attributes.add(new CognitoUserAttribute("email", account.getEmail()));
                    // 自定义属性需提前在Cognito用户池的属性设置中添加
                    attributes.add(new CognitoUserAttribute("custom:google_token", account.getIdToken()));

                    // 更新用户池中的用户属性
                    cognitoUser.updateAttributesInBackground(attributes, new CognitoUserUpdateAttributesHandler() {
                        @Override
                        public void onSuccess(List<CognitoUserAttribute> attributesList) {
                            Log.i(TAG, "用户属性存入用户池成功");
                        }

                        @Override
                        public void onFailure(Exception exception) {
                            Log.e(TAG, "存入用户属性失败", exception);
                        }
                    });
                }
            }

            @Override
            public void onError(Exception e) {
                Log.e(TAG, "sign-in error", e);
            }
        });
    }

    @Override
    public void onError(Exception e) {
        Log.e(TAG, "初始化失败", e);
    }
});

关键说明

  • 自定义属性(如custom:google_token)需要提前在Cognito用户池的「属性」设置中创建,类型选择字符串
  • 首次通过第三方登录Cognito用户池时,系统会自动创建对应用户,此时可直接更新属性完成数据存入
  • 第三方Token存储需评估安全性,仅保留必要凭证,避免敏感信息过度暴露

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:00:52