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

将Google登录集成到Amazon Cognito用户池的Android技术问询

Let’s break down exactly what you need to do next, since you already have a working Google Sign-In flow and ID token in hand.

First: Confirm Cognito & Google Setup

Before diving into code, double-check these key configurations in the AWS Console:

  • In your Cognito User Pool, go to Identity providers > Google and ensure:
    • You’ve entered your Google client ID/secret correctly.
    • Scopes include openid, email, and profile (matches what you’re requesting in your GoogleSignInOptions).
    • Attribute mapping is set up (e.g., map Google’s email to Cognito’s email attribute).
  • You already added your Cognito user pool domain URL to Google’s authorized redirect URIs—great, that’s needed if you ever use the hosted UI, but even for direct federation, it’s good to have in place.

Do You Need to Configure Callback/Sign-Out URLs in the App Client?

Yes, you should. Even though you’re handling Google sign-in yourself, these URLs are required for Cognito to properly manage session state (especially if you ever use features like sign-out or password reset via the hosted UI). Here’s how to set them:

  1. Go to your User Pool > App integration > App clients and analytics > Select your Android app client.
  2. Under App client settings:
    • For Callback URL(s): Use a custom deep link scheme your app can handle (e.g., yourappname://cognito/callback).
    • For Sign-out URL(s): Use a similar scheme (e.g., yourappname://cognito/signout).
  3. Ensure Enabled Identity Providers includes Google.

Linking Google ID Token to Cognito (Two Scenarios)

Since you already have the Google ID token, you can skip the Cognito OAuth/hosted UI flow entirely. Instead, use direct federation with Cognito’s APIs. Here are the two common use cases:

Scenario 1: Sign In/Create User with Google (Federated Authentication)

This will either create a new Cognito user linked to the Google identity, or sign in an existing user who already linked their Google account.

Using AWS Amplify (Recommended for Android)

Amplify simplifies Cognito interactions significantly. After getting your Google ID token:

// After retrieving idToken from handleSignInResult
Map<String, String> googleTokens = new HashMap<>();
googleTokens.put("id_token", idToken);

AWSMobileClient.getInstance().federatedSignIn(
    "Google", // Must match the exact name of your Google IdP in Cognito
    googleTokens,
    new Callback<UserStateDetails>() {
        @Override
        public void onResult(UserStateDetails result) {
            // Success: User is now signed into Cognito with their Google identity
            Log.d(TAG, "Federated sign-in successful: " + result.getUserState());
        }

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

Using Low-Level Cognito API (If You Avoid Amplify)

If you prefer not to use Amplify, use the AWSCognitoIdentityProvider client:

AWSCognitoIdentityProvider cognitoClient = AWSCognitoIdentityProviderClientBuilder.standard()
    .withRegion(Regions.YOUR_AWS_REGION)
    .build();

AdminInitiateAuthRequest authRequest = new AdminInitiateAuthRequest()
    .withUserPoolId("YOUR_USER_POOL_ID")
    .withClientId("YOUR_APP_CLIENT_ID")
    .withAuthFlow(AuthFlowType.CUSTOM_AUTH)
    .withAuthParameters(new HashMap<String, String>() {{
        put("ID_TOKEN", idToken);
        put("PROVIDER_NAME", "Google");
    }});

try {
    AdminInitiateAuthResult authResult = cognitoClient.adminInitiateAuth(authRequest);
    // Use authResult.getAuthenticationResult() to get Cognito tokens
    Log.d(TAG, "Cognito sign-in successful");
} catch (Exception e) {
    Log.e(TAG, "Cognito sign-in failed", e);
}

If the user already has a Cognito account (e.g., signed up with email/password), link their Google identity to it after they’re signed into Cognito:

Using Amplify

// Ensure the user is already signed into their Cognito account first
Map<String, String> googleTokens = new HashMap<>();
googleTokens.put("id_token", idToken);

AWSMobileClient.getInstance().linkUser(
    "Google",
    googleTokens,
    new Callback<UserStateDetails>() {
        @Override
        public void onResult(UserStateDetails result) {
            Log.d(TAG, "Google identity linked to Cognito user successfully");
        }

        @Override
        public void onError(Exception e) {
            Log.e(TAG, "Failed to link identity", e);
        }
    }
);

Can You Skip the OAuth Flow?

Absolutely! Since you’ve already handled the Google sign-in flow and obtained a valid ID token, you don’t need to use Cognito’s hosted OAuth flow (which redirects users to a web page). Directly passing the Google ID token to Cognito via the methods above is a fully supported approach.

Common Pitfalls to Avoid

  • Case-sensitive Provider Name: The "Google" string in the code must exactly match the name you gave to your Google IdP in the Cognito console.
  • Token Expiry: Google ID tokens expire after 1 hour—make sure you’re using a fresh token when sending to Cognito.
  • Attribute Mapping: If Cognito rejects the token, check that all required attributes (like email) are mapped correctly between Google and Cognito.

内容的提问来源于stack exchange,提问作者Lee Yee Run

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:57:49