Initiate Google Account Linking directly from your platform.

Account Linking can be initiated directly on your app, allowing users of your service to link their account, on your service, with their Google Account without leaving your app. The established link grants Google access to the data the user consents to share. This results in an increase in the number of linked accounts by providing multiple entry points to the linking process.

How it works

Link from your Platform is completed in the following steps:

  1. User will click / toggle a linking trigger on your app.
  2. The user selects the Google account to link.
    1. The signs into their Google account if there is no signed-in account on the device.
  3. The user is shown a Google hosted consent screens.
  4. The user is shown your consent screen and agrees or opts-out of sharing their data.
  5. Link is established between the user’s account, on your service, and their Google account.

Figure 1. Link from your Platform Flow

Setup

Before proceeeding with the steps below, you must have completed the Account Linking registration process.

Setup your development environment

Get the latest Google Play services on your development host:

  1. Open the Android SDK Manager.
  1. Under SDK Tools, find Google Play services.

  2. If the status for these packages is not Installed, select them both and click Install Packages.

Configure your app

  1. In your project-level build.gradle file, include Google's Maven repository in both your buildscript and allprojects sections.

    buildscript {
        repositories {
            google()
        }
    }
    
    allprojects {
        repositories {
            google()
        }
    }
    
  2. Add the dependencies for the “Link with Google” API to your module's app-level gradle file, which is usually app/build.gradle:

    dependencies {
      implementation 'com.google.android.gms:play-services-auth:19.2.0'
    }
    

The Link from your Platform flow will result in an access token, provided by your service, being saved by Google. Consent must be received before returning the token for the user.

Follow the steps below to get consent from the user and return an auth code token via the Google Play Services SDK.

  1. Build a PendingIntent that can launch your consent activity - The consent is launched by the Play Services API. You will need to provide a PendingIntent (which will be referred to as the consentPendingIntent for clarity) when the API is called

    Kotlin

    // Build a PendingIntent that can launch the consent activity
    val consentPendingIntent = buildConsentPendingIntent()
    

    Java

    // Build a PendingIntent that can launch your consent activity
    PendingIntent consentPendingIntent =
              buildConsentPendingIntent();
    
  2. Create corresponding Activity to handle the consent intent

    Kotlin

      class ConsentActivity : AppCompatActivity
    
      private fun onConsentAccepted() {
          // Obtain a token (for simplicity, we’ll ignore the async nature
          // of the following call)
          val token = getToken()
          val intent = Intent()
                      .putExtra(SaveAccountLinkingTokenRequest.EXTRA_TOKEN,
                                token)
          setResult(Activity.RESULT_OK, intent)
          finish()
      }
    
      private fun onConsentRejectedOrCanceled() {
          setResult(Activity.RESULT_CANCELED)
          finish()
      }
    

    Java

      public class ConsentActivity extends AppCompatActivity {
        ...
        private void onConsentAccepted() {
          // Obtain a token (for simplicity, we’ll ignore the async nature of
          // the following call
          String token = getToken();
          Intent intent = new Intent();
          intent.putExtra(SaveAccountLinkingTokenRequest.EXTRA_TOKEN, token);
          setResult(Activity.RESULT_OK, intent);
          finish();
        }
    
        private void onConsentRejectedOrCanceled() {
          setResult(Activity.RESULT_CANCELED, null);
          finish();
        }
     }
    
    

    We assume that the methods onConsentAccpeted() and onConsentRejectedOrCanceled() are called if user accepts or rejects/cancels your consent, respectively.

  3. Create a request for saving the token and, among other configuration parameters, pass the PendingIntent created in step 1 above.

    Kotlin

      // Create an ActivityResultLauncher which registers a callback for the
      // Activity result contract
      val activityResultLauncher = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult())
        { result ->
          if (result.resultCode == RESULT_OK) {
            // Successfully finished the flow and saved the token
          } else {
            // Flow failed, for example the user may have canceled the flow
          }
        }
    
      // Build token save request
      val request = SaveAccountLinkingTokenRequest.builder()
        .setTokenType(SaveAccountLinkingTokenRequest.TOKEN_TYPE_AUTH_CODE)
        .setConsentPendingIntent(consentPendingIntent)
        .setServiceId("service-id-of-and-defined-by-developer")
        //Set the scopes that the token is valid for on your platform
        .setScopes(scopes)
        .build()
    
       // Launch consent activity and retrieve token
       Identity.getCredentialSavingClient(this)
         .saveAccountLinkingToken(request)
         .addOnSuccessListener( saveAccountLinkingTokenResult -> {
            if (saveAccountLinkingTokenResult.hasResolution()) {
              val pendingIntent = saveAccountLinkingTokenResult
                                  .getPendingIntent()
              val intentSenderRequest = IntentSenderRequest
                                        .Builder(pendingIntent).build()
              activityResultLauncher.launch(intentSenderRequest)
            } else {
               // This should not happen, let’s log this
               Log.e(TAG, "Failed to save token");
            }
          })
          .addOnFailureListener(e -> Log.e(TAG, “Failed to save token”, e))
    

    Java

      // Create an ActivityResultLauncher which registers a callback for the
      // Activity result contract
      private final ActivityResultLauncher<IntentSenderRequest>
          activityResultLauncher =
          registerForActivityResult(ActivityResultContracts
                                        .StartIntentSenderForResult(),
                                    result -> {
          if (result.getResultCode() == RESULT_OK) {
              // Successfully finished the flow and saved the token
          } else {
              // Flow failed, for example the user may have canceled the flow
          }
      });
    
     // Build token save request
     SaveAccountLinkingTokenRequest request =
        SaveAccountLinkingTokenRequest.builder()
            .setTokenType(
                SaveAccountLinkingTokenRequest.TOKEN_TYPE_AUTH_CODE)
            .setConsentPendingIntent(consentPendingIntent)
            .setServiceId("service-id-of-and-defined-by-developer")
            //Set the scopes that the token is valid for on your platform
            .setScopes(scopes)
            .build();
    
      // Launch consent activity and retrieve token
      Identity.getCredentialSavingClient(this)
          .saveAccountLinkingToken(request)
          .addOnSuccessListener(
              saveAccountLinkingTokenResult -> {
                if (saveAccountLinkingTokenResult.hasResolution()) {
                  // Launch the resolution intent
                  PendingIntent pendingIntent =
                      saveAccountLinkingTokenResult.getPendingIntent();
                  IntentSenderRequest intentSenderRequest =
                      IntentSenderRequest.Builder(pendingIntent).build();
                  activityResultLauncher.launch(intentSenderRequest);
                } else {
                  // This should not happen, let’s log this
                  Log.e(TAG, "Failed to save token");
                }
              })
          .addOnFailureListener(e -> Log.e(TAG, "Failed to save token", e));
      ```
    

The above steps prompts a user for consent and returns an authorization code to Google.

Reference

Android auth api reference documentation