public final class

GoogleAuthUtil

extends Object
java.lang.Object
   ↳ com.google.android.gms.auth.GoogleAuthUtil

Class Overview

GoogleAuthUtil provides static utility methods to acquire and invalidate authentication tokens.

   public void onCreate {
       // onCreate is called on the main thread, so you must do the work in
       // a background thread, which AsyncTask makes easy to do.
       getAndUseAuthTokenInAsyncTask();
   }

   ...

   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (requestCode == MY_ACTIVITYS_AUTH_REQUEST_CODE) {
           if (resultCode == RESULT_OK) {
               getAndUseAuthTokenInAsyncTask();
           }
       }
   }

   // Example of how to use the GoogleAuthUtil in a blocking, non-main thread context
   void getAndUseAuthTokenBlocking() {
       try {
          // Retrieve a token for the given account and scope. It will always return either
          // a non-empty String or throw an exception.
          final String token = GoogleAuthUtil.getToken(context, email, scope);
          // Do work with token.
          ...
          if (server indicates token is invalid) {
              // invalidate the token that we found is bad so that GoogleAuthUtil won't
              // return it next time (it may have cached it)
              GoogleAuthUtil.invalidateToken(Context, String)(context, token);
              // consider retrying getAndUseTokenBlocking() once more
              return;
          }
          return;
       } catch (GooglePlayServicesAvailabilityException playEx) {
         Dialog alert = GooglePlayServicesUtil.getErrorDialog(
             playEx.getConnectionStatusCode(),
             this,
             MY_ACTIVITYS_AUTH_REQUEST_CODE);
         ...
       } catch (UserRecoverableAuthException userAuthEx) {
          // Start the user recoverable action using the intent returned by
          // getIntent()
          myActivity.startActivityForResult(
                  userAuthEx.buildIntent(),
                  MY_ACTIVITYS_AUTH_REQUEST_CODE);
          return;
       } catch (IOException transientEx) {
          // network or server error, the call is expected to succeed if you try again later.
          // Don't attempt to call again immediately - the request is likely to
          // fail, you'll hit quotas or back-off.
          ...
          return;
       } catch (GoogleAuthException authEx) {
          // Failure. The call is not expected to ever succeed so it should not be
          // retried.
          ...
          return;
       }
   }

   // Example of how to use AsyncTask to call blocking code on a background thread.
   void getAndUseAuthTokenInAsyncTask() {
       AsyncTask task = new AsyncTask() {
           @Override
           protected Void doInBackground(Void... params) {
               getAndUseAuthTokenBlocking();
           }
       };
       task.execute((Void)null);
   }
 

Summary

Constants
int CHANGE_TYPE_ACCOUNT_ADDED Change types that can be represented in an AccountChangeEvent.
int CHANGE_TYPE_ACCOUNT_REMOVED
int CHANGE_TYPE_ACCOUNT_RENAMED_FROM A rename event that will contain extra data indicating the original account name.
int CHANGE_TYPE_ACCOUNT_RENAMED_TO A rename event that will contain extra data indicating the new account name.
String GOOGLE_ACCOUNT_TYPE Google Account type string.
String KEY_REQUEST_ACTIONS Bundle key for specifying which user's app activity (moment) types can be written to Google.
String KEY_REQUEST_VISIBLE_ACTIVITIES See KEY_REQUEST_ACTIONS
String KEY_SUPPRESS_PROGRESS_SCREEN Adding KEY_SUPPRESS_PROGRESS will suppress the progress screen shown when getting a token when added as a boolean true option while calling getToken(Context, String, String, Bundle).
Public Methods
static void clearToken(Context context, String token)
Clear the specified token in local cache with respect to the Context.
static List<AccountChangeEvent> getAccountChangeEvents(Context ctx, int eventIndex, String accountName)
Get a list of events for the given account.
static String getAccountId(Context ctx, String accountName)
Gets a stable account id for the given account name.
static String getAppCert(Context context, String packageNameToCertify)
static String getToken(Context context, String accountName, String scope)
static String getToken(Context context, String accountName, String scope, Bundle extras)
Gets a token to be consumed by some specified services on behalf of a specified user account.
static String getTokenWithNotification(Context context, String accountName, String scope, Bundle extras)
Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.
static String getTokenWithNotification(Context context, String accountName, String scope, Bundle extras, Intent callback)
Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.
static String getTokenWithNotification(Context context, String accountName, String scope, Bundle extras, String authority, Bundle syncBundle)
Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.
static void invalidateToken(Context context, String token)
This method is deprecated. Deprecated because this function needs permissions MANAGE_ACCOUNTS and USE_CREDENTIALS to run. Please call clearToken(Context, String) instead.
[Expand]
Inherited Methods
From class java.lang.Object

Constants

public static final int CHANGE_TYPE_ACCOUNT_ADDED

Change types that can be represented in an AccountChangeEvent.

Constant Value: 1 (0x00000001)

public static final int CHANGE_TYPE_ACCOUNT_REMOVED

Constant Value: 2 (0x00000002)

public static final int CHANGE_TYPE_ACCOUNT_RENAMED_FROM

A rename event that will contain extra data indicating the original account name.

Constant Value: 3 (0x00000003)

public static final int CHANGE_TYPE_ACCOUNT_RENAMED_TO

A rename event that will contain extra data indicating the new account name.

Constant Value: 4 (0x00000004)

public static final String GOOGLE_ACCOUNT_TYPE

Google Account type string. Used for various calls to AccountManager.

Constant Value: "com.google"

public static final String KEY_REQUEST_ACTIONS

Bundle key for specifying which user's app activity (moment) types can be written to Google. The list of activity types are represented as a space-separated string passed in the extras Bundle when calling getToken(Context, String, String, Bundle).

This bundle key should be included in the extras Bundle when calling getToken(Context, String, String, Bundle) and should only be used when requesting the PLUS_LOGIN OAuth 2.0 scope. See Types of moments for the full list of valid activity types. Example usage:

     Bundle bundle = new Bundle();
     bundle.putString(GoogleAuthUtil.KEY_REQUEST_ACTIONS,
              "http://schemas.google.com/AddActivity http://schemas.google.com/BuyActivity");
     String token = GoogleAuthUtil.getToken(context, accountName, Scopes.PLUS_LOGIN, bundle);
 

Constant Value: "request_visible_actions"

public static final String KEY_REQUEST_VISIBLE_ACTIVITIES

Constant Value: "request_visible_actions"

public static final String KEY_SUPPRESS_PROGRESS_SCREEN

Adding KEY_SUPPRESS_PROGRESS will suppress the progress screen shown when getting a token when added as a boolean true option while calling getToken(Context, String, String, Bundle). This is useful for apps that provide their own splash screens on initialization.

Constant Value: "suppressProgressScreen"

Public Methods

public static void clearToken (Context context, String token)

Clear the specified token in local cache with respect to the Context. Note that the context must be the same as that used to initialize the token in a previous call to getToken(Context, String, String) or getToken(Context, String, String, Bundle).

Parameters
context Context of the token.
token The token to clear.

public static List<AccountChangeEvent> getAccountChangeEvents (Context ctx, int eventIndex, String accountName)

Get a list of events for the given account. The result is in reverse chronological order.

Parameters
eventIndex An event index to restrict results by. If 0 then all events will be fetched. Otherwise, events greater than this index will be fetched. Callers can store the last event index seen and use this field to limit results to only events more recent than the ones seen prior.
accountName The account name to restrict the event list to.
Throws
GoogleAuthException
IOException

public static String getAccountId (Context ctx, String accountName)

Gets a stable account id for the given account name. In the event of a missing id, user intervention may be required. In such cases, a UserRecoverableAuthException will be thrown. To initiate the user recovery workflow, clients must start the Intent returned by getIntent() for result. Upon successfully returning a client should invoke this method again to get an id.

Throws
GooglePlayServicesAvailabilityException containing the appropriate connection status error code.
UserRecoverableAuthException wrapping an Intent for initiating user intervention. The wrapped intent must be called with startActivityForResult(Intent, int).
GoogleAuthException signaling a potentially unrecoverable authentication error.
IOException signaling a potentially transient error.
IllegalStateException if the method is invoked in the main event thread.

public static String getAppCert (Context context, String packageNameToCertify)

public static String getToken (Context context, String accountName, String scope)

public static String getToken (Context context, String accountName, String scope, Bundle extras)

Gets a token to be consumed by some specified services on behalf of a specified user account. How the token is consumed depends on the scope string provided. Note that this method requires substantial network IO and thus should be run off the UI thread. In the event of an error, one of several Exceptions will be thrown.

In the case of a transient (typically network related) error a IOException will be thrown. It is left to clients to implement a backoff/abandonment strategy appropriate to their latency requirements. If user intervention is required to provide consent, enter a password, etc, a UserRecoverableAuthException will be thrown. To initiate the user recovery workflow, clients must start the Intent returned by getIntent() for result. Upon successfully returning a client should invoke this method again to get a token. In the cases of errors that are neither transient nor recoverable by the the user, a GoogleAuthException will be thrown. These errors will typically result from client errors (e.g. providing an invalid scope).

By way of example, client code might have a block of code executing in a locally declared implementation of Thread or AsyncTask as follows:

 String token = null;
 try {
     token = GoogleAuthUtil.getToken(context, accountName, scope, bundle);
 } catch (GooglePlayServicesAvailabilityException playEx) {
     Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
         playEx.getConnectionStatusCode(),
         Activity.this,
         AUTH_REQUEST_CODE);
     // Use the dialog to present to the user.
 } catch (UserRecoverableAuthException recoverableException) {
     Intent recoveryIntent = recoverableException.buildIntent();
     // Use the intent in a custom dialog or just startActivityForResult.
     Activity.this.startActivityForResult(recoveryIntent, REQUEST_CODE);
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMessage(), authEx);
     return;
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
     return;
 }
 if (token != null) {
     makeNetworkApiCallwithToken(token);
 }
 

Those clients that have their own splash screens may wish to suppress the progress screen provided by Google Play services. The "Signing in..." progress screen provided by Google Play services by including setting KEY_SUPPRESS_PROGRESS_SCREEN to true in the supplied options Bundle.

Parameters
context Context associated with the desired token.
accountName String representing the authenticating user account.
scope String representing the authentication scope. To specify multiple scopes, separate them with a space (for example, "oauth2:scope1 scope2 scope3").
extras Bundle containing additional information that may be relevant to the authentication scope.
Returns
  • String containing a valid token.
Throws
GooglePlayServicesAvailabilityException containing the appropriate connection status error code.
UserRecoverableAuthException wrapping an Intent for initiating user intervention. The wrapped intent must be called with startActivityForResult(Intent, int).
GoogleAuthException signaling a potentially unrecoverable authentication error.
IOException signaling a potentially transient error.
IllegalStateException if the method is invoked in the main event thread.

public static String getTokenWithNotification (Context context, String accountName, String scope, Bundle extras)

Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.

This method is specifically provided for background tasks. In the event of an error that needs user intervention, this method takes care of pushing relevant notification.

The exception thrown depends upon the underlying error and support for recovery. UserRecoverableNotifiedException will be thrown if the error can be resolved by user intervention and a notification has already been posted to address it. IOExceptions will be thrown if the underlying error might be solved by some intelligent retry strategy. Alternatively, GoogleAuthExceptions represent a broad class of Exceptions that cannot be recovered programmatically.

 String token;
 try {
     token = GoogleAuthUtil.getTokenWithNotification(context, accountName, scope, extras);
 } catch (UserRecoverableNotifiedException userNotifiedException) {
     // Notification has already been pushed.
     // Continue without token or stop background task.
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMessage(), authEx);
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
 }
 

Parameters
context Context associated with the desired token.
accountName String representing the authenticating user account.
scope String representing the authentication scope. To specify multiple scopes, separate them with a space (for example, "oauth2:scope1 scope2 scope3").
extras Bundle containing additional information that may be relevant to the authentication scope.
Returns
  • String containing a valid token.
Throws
UserRecoverableNotifiedException if a user addressable error occurred and a notification was pushed.
GoogleAuthException signaling a potentially unrecoverable authentication error.
IOException signaling a potentially transient error.
IllegalStateException if the method is invoked in the main event thread.

public static String getTokenWithNotification (Context context, String accountName, String scope, Bundle extras, Intent callback)

Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.

This method is specifically provided for background tasks. In the event of an error that needs user intervention, this method takes care of pushing relevant notification. After the user addresses the notification, the callback is broadcasted. If the user cancels then the callback is not fired.

The exception thrown depends upon the underlying error and support for recovery. UserRecoverableNotifiedException will be thrown if the error can be resolved by user intervention and a notification has already been posted to address it. IOExceptions will be thrown if the underlying error might be solved by some intelligent retry strategy. Alternatively, GoogleAuthExceptions represent a broad class of Exceptions that cannot be recovered programmatically.

 String token;
 try {
     token = GoogleAuthUtil.getTokenWithNotification(
         context, accountName, scope, extras, callback);
 } catch (UserRecoverableNotifiedException userNotifiedException) {
     // Notification has already been pushed.
     // Continue without token or stop background task.
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMessage(), authEx);
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
 }
 

Parameters
context Context associated with the desired token.
accountName String representing the authenticating user account.
scope String representing the authentication scope. To specify multiple scopes, separate them with a space (for example, "oauth2:scope1 scope2 scope3").
extras Bundle containing additional information that may be relevant to the authentication scope.
callback A broadcast intent with a valid receiver that has been exported for other apps to send broadcasts to it. This intent must be serializable using toUri(Intent.URI_INTENT_SCHEME) and Intent.parseUri(intentUri, Intent.URI_INTENT_SCHEME). Cannot be null.
Returns
  • String containing a valid token.
Throws
UserRecoverableNotifiedException if a user addressable error occurred and a notification was pushed.
GoogleAuthException signaling a potentially unrecoverable authentication error.
IOException signaling a potentially transient error.
IllegalStateException if the method is invoked in the main event thread.

public static String getTokenWithNotification (Context context, String accountName, String scope, Bundle extras, String authority, Bundle syncBundle)

Authenticates the user and returns a valid Google authentication token, or throws an Exception if there was an error while getting the token.

This method is specifically provided for sync adaptors. In the event of an error that needs user intervention, this method takes care of pushing relevant notification. After the user addresses the notification, a sync request will be kicked off using the given params. If the user cancels then the sync is not fired.

The exception thrown depends upon the underlying error and support for recovery. UserRecoverableNotifiedException will be thrown if the error can be resolved by user intervention and a notification has already been posted to address it. IOExceptions will be thrown if the underlying error might be solved by some intelligent retry strategy. Alternatively, GoogleAuthExceptions represent a broad class of Exceptions that cannot be recovered programmatically.

 String token;
 try {
     token = GoogleAuthUtil.getTokenWithNotification(
         context, accountName, scope, extras, authority, syncBundle);
 } catch (UserRecoverableNotifiedException userNotifiedException) {
     // Notification has already been pushed.
     // Continue without token or stop background task.
 } catch (GoogleAuthException authEx) {
     // This is likely unrecoverable.
     Log.e(TAG, "Unrecoverable authentication exception: " + authEx.getMessage(), authEx);
 } catch (IOException ioEx) {
     Log.i(TAG, "transient error encountered: " + ioEx.getMessage());
     doExponentialBackoff();
 }
 

Parameters
context Context associated with the desired token.
accountName String representing the authenticating user account.
scope String representing the authentication scope. To specify multiple scopes, separate them with a space (for example, "oauth2:scope1 scope2 scope3").
extras Bundle containing additional information that may be relevant to the authentication scope.
authority Authority for firing a sync request. Must not be empty or null.
syncBundle extras for firing a sync request. This bundle must pass ContentResolver.validateSyncExtrasBundle(). If no extras are needed can a null value can be passed.
Returns
  • String containing a valid token.
Throws
UserRecoverableNotifiedException if a user addressable error occurred and a notification was pushed.
GoogleAuthException signaling a potentially unrecoverable authentication error.
IOException signaling a potentially transient error.
IllegalStateException if the method is invoked in the main event thread.

public static void invalidateToken (Context context, String token)

This method is deprecated.
Deprecated because this function needs permissions MANAGE_ACCOUNTS and USE_CREDENTIALS to run. Please call clearToken(Context, String) instead.

Invalidates the specified token with respect to the Context. Note that the context must be the same as that used to initialize the token in a previous call to getToken(Context, String, String) or getToken(Context, String, String, Bundle).

Parameters
context Context of the token.
token String containing the token to invalidate.