Authorize access to Google user data

Authentication establishes who someone is, and is commonly referred to as user sign-up or sign-in. Authorization is the process of granting or rejecting access to data or resources. For example, your app requests your user's consent to access the user's Google Drive.

Authentication and authorization calls should be two separate and distinct flows based on the needs of the app.

If your app has features that can make use of Google API data, but are not required as part of your app's core features, you should design your app to be able to gracefully handle cases when API data isn't accessible. For example, you might hide a list of recently saved files when the user hasn't granted Drive access.

You should request access to scopes that you need to access Google APIs only when the user performs an action that requires access to a particular API. For example, you should request permission to access the user's Drive whenever the user taps a "Save to Drive" button.

By separating authorization from authentication, you can avoid overwhelming new users, or confusing users as to why they are being asked for certain permissions.

For authentication, we recommend using the Credential Manager API. For authorizing actions that need access to user data stored by Google, we recommend using AuthorizationClient.

Set up your Google Cloud Console project

  1. Open your project in the Cloud Console, or create a project if you don't already have one.
  2. On the Branding page, make sure all of the information is complete and accurate.
    1. Make sure your app has a correct App Name, App Logo, and App Homepage assigned. These values will be presented to users on the Sign in with Google consent screen on sign up and the Third-party apps & services screen.
    2. Make sure you have specified the URLs of your app's privacy policy and terms of service.
  3. In the Clients page, create an Android client ID for your app if you don't already have one. You will need to specify your app's package name and SHA-1 signature.
    1. Go to the Clients page.
    2. Click Create client.
    3. Select the Android application type.
  4. In the Clients page, create a new "Web application" client ID if you haven't already. You can ignore the "Authorized JavaScript Origins" and "Authorized redirect URIs" fields for now. This client ID will be used to identify your backend server when it communicates with Google's authentication services.
    1. Go to the Clients page.
    2. Click Create client.
    3. Select the Web application type.

Declare dependencies

In your module's build.gradle file, declare dependencies using the latest version of the Google Identity Services library.

dependencies {
  // ... other dependencies

  implementation "com.google.android.gms:play-services-auth:<latest version>"
}

Request permissions required by user actions

Whenever a user performs an action that requires additional scope, call AuthorizationClient.authorize().

For example, if a user performs an action that requires access to their Drive app storage, do the following:

List<Scopes> requestedScopes = Arrays.asList(DriveScopes.DRIVE_APPDATA);
AuthorizationRequest authorizationRequest = AuthorizationRequest.builder().setRequestedScopes(requestedScopes).build();
Identity.getAuthorizationClient(this)
        .authorize(authorizationRequest)
        .addOnSuccessListener(
            authorizationResult -> {
              if (authorizationResult.hasResolution()) {
                    // Access needs to be granted by the user
                PendingIntent pendingIntent = authorizationResult.getPendingIntent();
                try {
startIntentSenderForResult(pendingIntent.getIntentSender(),
REQUEST_AUTHORIZE, null, 0, 0, 0, null);
                } catch (IntentSender.SendIntentException e) {
                Log.e(TAG, "Couldn't start Authorization UI: " + e.getLocalizedMessage());
                }
              } else {
            // Access already granted, continue with user action
                saveToDriveAppFolder(authorizationResult);
              }
            })
        .addOnFailureListener(e -> Log.e(TAG, "Failed to authorize", e));

In your activity's onActivityResult callback, you can check if the required permissions were successfully acquired, and if so, carry out the user action.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (requestCode == MainActivity.REQUEST_AUTHORIZE) {
    AuthorizationResult authorizationResult = Identity.getAuthorizationClient(this).getAuthorizationResultFromIntent(data);
    saveToDriveAppFolder(authorizationResult);
  }
}

If you are accessing Google APIs on the server side, you can call the getServerAuthCode() method of AuthorizationResult to get an auth code which you send to your backend to exchange for an access and refresh token.