Auth0.Android Save and Renew Tokens
When an authentication is performed with the offline_access
scope included, it will return a Refresh Token that can be used to request a new user token, without forcing the user to perform authentication again.
Credentials Manager
Auth0.Android provides a utility class to streamline the process of storing and renewing credentials. You can access the accessToken
or idToken
properties from the Credentials instance. This is the preferred method to manage user credentials.
Credential Managers are included as part of the Auth0.Android SDK. If this is not part of your dependencies yet, make sure to check the documentation.
Next, decide which class to use depending on your Android SDK target version.
API less than 21
If you require APIs lower than 21 (Lollipop) create a new instance of CredentialsManager
. This class makes use of the Context.MODE_PRIVATE
to store the credentials in a key-value preferences file, accessible only to your app. The data is stored in plaintext.
API equal to or greater than 21
If you require APIs equal or greater than 21 (Lollipop) create a new instance of SecureCredentialsManager
. This class has the same methods as the one above, but encrypts the data before storing it using a combination of RSA and AES algorithms along with the use of Android KeyStore.
Using the CredentialsManager class
Set up the CredentialsManager
Create a new instance by passing an AuthenticationAPIClient
and a Storage
implementation.
Auth0 auth0 = new Auth0(this);
AuthenticationAPIClient apiClient = new AuthenticationAPIClient(auth0);
CredentialsManager manager = new CredentialsManager(apiClient, new SharedPreferencesStorage(this));
Current State of the Authentication
Stored credentials are considered valid if they have not expired or can be refreshed. Check if a user has already logged in:
boolean loggedIn = manager.hasValidCredentials();
When you want to log the user out of your app, remove the stored credentials and direct them to the login screen.
manager.clearCredentials();
Retrieving Credentials
Because the credentials may need to be refreshed against Auth0 Servers, this method is asynchronous. Pass a callback implementation where you'd like to receive the credentials. Credentials returned by this method upon success are always valid.
manager.getCredentials(new BaseCallback<Credentials, CredentialsManagerException>() {
@Override
public void onSuccess(Credentials credentials) {
//Use credentials
}
@Override
public void onFailure(CredentialsManagerException error) {
//No credentials were previously saved or they couldn't be refreshed
}
});
If the accessToken
has expired, the manager will automatically use the refreshToken
and renew the credentials for you. New credentials will be stored for future access.
Save new Credentials
You can save the credentials obtained during authentication in the manager.
manager.saveCredentials(credentials);
Using the SecureCredentialsManager class
Set up the SecureCredentialsManager
The CredentialsManager class set up is a little different. Create a new instance by passing a valid android Context
, an AuthenticationAPIClient
and a Storage
implementation.
Auth0 auth0 = new Auth0(this);
AuthenticationAPIClient apiClient = new AuthenticationAPIClient(auth0);
SecureCredentialsManager manager = new SecureCredentialsManager(this, apiClient, new SharedPreferencesStorage(this));
The methods to obtain, save, check for existence and clearing the credentials are the ones explained before.
Pre-Authenticate the User
This class provides optional functionality for additional authentication using the device's configured Lock Screen. If the Lock Screen Security is set to something different than PIN, Pattern, Password or Fingerprint, this feature won't be available. You need to call the method below to enable the authentication. Pass a valid Activity
context, a request code, and 2 optional Strings to use as title and description for the Lock Screen.
private static final int RC_UNLOCK_AUTHENTICATION = 123;
//Called from an Activity
boolean available = manager.requireAuthentication(this, RC_UNLOCK_AUTHENTICATION, getString(R.string.unlock_authentication_title), getString(R.string.unlock_authentication_description));
If the feature was enabled, the manager will prompt the user to authenticate using the configured Lock Screen. The result of this call will be obtained in the onActivityResult
method of the activity passed before as first parameter. If the feature was not enabled, Lock Screen authentication will be skipped.
After checking that the received request code matches the one used in the configuration step, redirect the received parameters to the manager to finish the authentication. The credentials will be yield to the original callback.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RC_UNLOCK_AUTHENTICATION && manager.checkAuthenticationResult(requestCode, resultCode)) {
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
Handling usage exceptions
In the event that something happened while trying to save or retrieve the Credentials, a CredentialsManagerException
will be thrown. These are some of the failure scenarios you can expect:
The Credentials to be stored are invalid, e.g. some of the following fields are not defined: access_token, id_token or expires_at.
The stored Credentials have expired but there is no refresh_token available to renew them automatically.
Device's Lock Screen security settings have changed (e.g. the security PIN code was changed). Even when
hasCredentials
returns true, the encryption keys will be deemed invalid and untilsaveCredentials
is called again it won't be possible to decrypt any previously existing content, since they keys used back then are not the same as the new ones.Device is not compatible with some of the cryptography algorithms required by the
SecureCredentialsManager
class. This is considered a catastrophic event and is the only exception that will prevent you from using this implementation. This scenario happens when the OEM has modified the Android ROM of the device removing some of the algorithms officially included in every Android distribution. Nevertheless, you can check if this is the case in the exception instance itself by calling theisDeviceIncompatible
method. By doing so you can decide the fallback implementation for storing the Credentials, such as using the regularCredentialsManager
class.