Retrieve a user's stored credentials

Automatically sign users into your app by using the Credentials API to request and retrieve stored credentials for your users.

Before you begin

Configure an Android Studio project.

Create a GoogleApiClient object

To request stored credentials, you must create an instance of GoogleApiClient configured to access the Credentials API.

mCredentialsApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .enableAutoManage(this, this)
    .addApi(Auth.CREDENTIALS_API)
    .build();

Create a CredentialRequest object

A CredentialRequest object specifies the sign-in systems from which you want to request credentials. Build a CredentialRequest using the setPasswordLoginSupported method for password-based sign-in, and the setAccountTypes() method for federated sign-in services such as Google Sign-In.

mCredentialRequest = new CredentialRequest.Builder()
    .setPasswordLoginSupported(true)
    .setAccountTypes(IdentityProviders.GOOGLE, IdentityProviders.TWITTER)
    .build();

Use the constants defined in IdentityProviders to specify commonly-used sign-in providers. For other sign-in providers, use any string that uniquely identifies the provider. You must use the same provider identifier to store credentials as you use to retrieve the credentials.

Request stored credentials

After you have created GoogleApiClient and CredentialRequest objects, pass them to the CredentialsApi.request() method to request credentials stored for your app.

Auth.CredentialsApi.request(mCredentialsClient, mCredentialRequest).setResultCallback(
    new ResultCallback<CredentialRequestResult>() {
        @Override
        public void onResult(CredentialRequestResult credentialRequestResult) {
            if (credentialRequestResult.getStatus().isSuccess()) {
                // See "Handle successful credential requests"
                onCredentialRetrieved(credentialRequestResult.getCredential());
            } else {
                // See "Handle unsuccessful and incomplete credential requests"
                resolveResult(credentialRequestResult.getStatus());
            }
        }
    });

Define a callback to handle successful and failed requests using the setResultCallback() method.

Handle successful credential requests

Toast indicating a successful sign in On a successful credential request, use the resulting Credential object to complete the user's sign-in to your app. Use the getAccountType() method to determine the type of retrieved credentials, then complete the appropriate sign-in process. For example, for Google Sign-In, create a GoogleApiClient object that includes the user's ID, then use the object to start the sign-in flow. For password-based sign-in, use the user's ID and password from the Credential object to complete your app's sign-in process.

private void onCredentialRetrieved(Credential credential) {
    String accountType = credential.getAccountType();
    if (accountType == null) {
        // Sign the user in with information from the Credential.
        signInWithPassword(credential.getId(), credential.getPassword());
    } else if (accountType.equals(IdentityProviders.GOOGLE)) {
        // The user has previously signed in with Google Sign-In. Silently
        // sign in the user with the same ID.
        // See https://developers.google.com/identity/sign-in/android/
        GoogleSignInOptions gso =
                new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                        .requestEmail()
                        .build();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, this)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .setAccountName(credential.getId())
                .build();
        OptionalPendingResult<GoogleSignInResult> opr =
                Auth.GoogleSignInApi.silentSignIn(mGoogleApiClient);
        // ...
    }
}

Handle multiple saved credentials

Smart Lock account chooser When user input is required to select a credential, the getStatusCode() method returns RESOLUTION_REQUIRED. In this case, call the status object's startResolutionForResult() method to prompt the user to choose an account. Then, retrieve the user's chosen credentials from the activity's onActivityResult() method by passing Credential.EXTRA_KEY to the getParcelableExtra() method.

private void resolveResult(Status status) {
    if (status.getStatusCode() == CommonStatusCodes.RESOLUTION_REQUIRED) {
        // Prompt the user to choose a saved credential; do not show the hint
        // selector.
        try {
            status.startResolutionForResult(this, RC_READ);
        } catch (IntentSender.SendIntentException e) {
            Log.e(TAG, "STATUS: Failed to send resolution.", e);
        }
    } else {
        // The user must create an account or sign in manually.
        Log.e(TAG, "STATUS: Unsuccessful credential request.");
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    ...

    if (requestCode == RC_READ) {
        if (resultCode == RESULT_OK) {
            Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
            onCredentialRetrieved(credential);
        } else {
            Log.e(TAG, "Credential Read: NOT OK");
            Toast.makeText(this, "Credential Read Failed", Toast.LENGTH_SHORT).show();
        }
    }

    ...

}

When stored credentials are not found, users must create an account or manually sign in. If getStatusCode() returns SIGN_IN_REQUIRED, you can optionally expedite the sign-up and sign-in processes by prompting the user to choose recently used sign-in information, such as email address and name, and automatically filling some fields of the forms with that information. See Provide sign-in hints to a user for details.

On successful sign in, allow users to save their credentials to automate future authentication on all their devices.