Android Session Handling

This tutorial shows you how to let users log in and maintain an active session with Auth0.

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • Android Studio 2.3
  • Android SDK 25
  • Emulator - Nexus 5X - Android 6.0
Show requirements

You need the Credentials class to handle users' credentials. The class is composed of these elements:

  • accessToken: Access Token used by the Auth0 API. To learn more, see the Access Token documentation.
  • idToken: Identity token that proves the identity of the user. To learn more, see the ID Token documentation.
  • refreshToken: Refresh Token that can be used to request new tokens without signing in again. To learn more, see the Refresh Token documentation.
  • tokenType: The type of tokens issued by the server.
  • expiresIn: The number of seconds before the tokens expire.
  • expiresAt: The date when the tokens expire.
  • scope: The scope that was granted to a user. This information is shown only if the granted scope is different than the requested one.

Tokens are objects used to prove your identity against the Auth0 APIs. Read more about them in the tokens documentation.

Before You Start

Before you continue with this tutorial, make sure that you have completed the Login tutorial.

Before you launch the login process, make sure you get a valid Refresh Token in the response. To do that, ask for the offline_access scope. Find the snippet in which you are initializing the WebAuthProvider class. To that snippet, add the line withScope("openid offline_access").

// app/src/main/java/com/auth0/samples/

Auth0 auth0 = new Auth0(this);
                .withAudience(String.format("https://%s/userinfo", getString(R.string.com_auth0_domain)))
                .withScope("openid offline_access")
                .start(LoginActivity.this, callback);

Save the User's Credentials

Save the user's credentials obtained in the login success response.

Make sure you use a secure method.

// app/src/main/java/com/auth0/samples/

private final AuthCallback callback = new AuthCallback() {
    public void onFailure(@NonNull final Dialog dialog) {
        //show error dialog

    public void onFailure(AuthenticationException exception) {
        //show error message

    public void onSuccess(@NonNull Credentials credentials) {

User credentials are stored in Private mode in the seed project in the SharedPreferences file. You can achieve this with the CredentialsManager class. For details, check the implementation in the project code. There are better and more secure ways to store tokens, but we will not cover them in this tutorial.

Check for Tokens when the Application Starts

To save your users the effort of logging in every time they open your app, use their Access Tokens. You can check for the Access Token when a user starts the app. If you find the token, you can automatically log the user in and direct them straight to your app's main flow.

// app/src/main/java/com/auth0/samples/

String accessToken = CredentialsManager.getCredentials(this).getAccessToken();
if (accessToken == null) {
  // Prompt Login screen.
} else {
  // Try to make an automatic login

Validate the Existing Token

If the Access Token exists, the next step is to check if it is valid. You can choose between two options:

  • Save the time when the user receives a new pair of credentials. When you need to use the Access Token, check how many seconds have passed since the user got the token. When the number exceeds the number specified in the expiresIn value, the token is no longer valid.
  • Call the Auth0 Authentication API and check the response.

This tutorial shows you how to call the Auth0 Authentication API with the /userinfo endpoint.

// app/src/main/java/com/auth0/samples/

AuthenticationAPIClient aClient = new AuthenticationAPIClient(auth0);
        .start(new BaseCallback<UserProfile, AuthenticationException>() {
            public void onSuccess(final UserProfile payload) {
                //Navigate to the next activity

            public void onFailure(AuthenticationException error) {
                //Delete current credentials and try again

You need to decide how to deal with an invalid token. Typically, you can choose between two options:

  • Ask the user to re-enter their credentials.
  • Use a Refresh Token to get a new valid Access Token.

This tutorial shows how to use a Refresh Token. If you want users to re-enter their credentials, clear the stored data and prompt the login screen.

Refresh the User's Session

Learn about Refresh Tokens

Before you go further with this tutorial, read the Refresh Token documentation. It is important that you remember the following:

  • Refresh Tokens must be securely saved.
  • Even though Refresh Tokens cannot expire, they can be revoked.
  • New tokens will never have a different scope than the scope you requested during the first login.

Create an AuthenticationAPIClient instance:

// app/src/main/java/com/auth0/samples/

AuthenticationAPIClient aClient = new AuthenticationAPIClient(auth0);

Use the Refresh Token to get new credentials:

// app/src/main/java/com/auth0/samples/

String refreshToken = CredentialsManager.getCredentials(this).getRefreshToken();
      .start(new BaseCallback<Credentials, AuthenticationException>() {

          public void onSuccess(Credentials payload) {
            String accessToken = payload.getAccessToken(); // New Access Token
            String idToken = payload.getIdToken(); // New ID Token
            //Save the new values

          public void onFailure(AuthenticationException error) {
            //show error

Log the User Out

To log the user out, you must remove their credentials and navigate them to the login screen.

For example, you can do the following:

// app/src/main/java/com/auth0/samples/

private void logout() {
  startActivity(new Intent(this, LoginActivity.class));

Depending on the way you store users' credentials, you delete them differently.

Optional: Encapsulate Session Handling

You can simplify the way you handle user sessions by storing token-related information and processes in a class. The class separates the logic for handling user sessions from the activity.

We recommend that you download the sample project from this tutorial and look at its implementation. Focus on the CredentialsManager class, which manages session handling, obtains user credentials from the SharedPreferences file and saves them.

Previous Tutorial
2. Login
Next Tutorial
4. User Profile
Was this article helpful?
Use Auth0 for FREECreate free Account