Retrofit — Token Authentication on Android

This tutorial in the Retrofit series describes and illustrates how to authenticate against any token based API from your Android app. This tutorial is an addition to the previous ones about basic authentication with Retrofit and using Retrofit for OAuth APIs. We’ll cover the topic of token authentication from an Android app to any web service or API supporting this kind of authentication.

Retrofit Series Overview

Integrate Token Authentication

If you read the previous tutorials about authentication with Retrofit, you’ll guess what we’re going to do: extend the ServiceGenerator class and integrate a method to handle token authentication. Let’s jump right in and extend the ServiceGenerator with a second createService method:

Retrofit 2

public class ServiceGenerator {

    public static final String API_BASE_URL = "https://your.api-base.url";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(
        Class<S> serviceClass, final String authToken) {
        if (!TextUtils.isEmpty(authToken)) {
            AuthenticationInterceptor interceptor =
                    new AuthenticationInterceptor(authToken);

            if (!httpClient.interceptors().contains(interceptor)) {
                httpClient.addInterceptor(interceptor);

                builder.client(httpClient.build());
                retrofit = builder.build();
            }
        }

        return retrofit.create(serviceClass);
    }
}

Retrofit 1.9

public class ServiceGenerator {

    public static final String API_BASE_URL = "https://your.api-base.url";

    private static RestAdapter.Builder builder = new RestAdapter.Builder()
                .setEndpoint(API_BASE_URL)
                .setClient(new OkClient(new OkHttpClient()));

    public static <S> S createService(Class<S> serviceClass) {
        return createService(serviceClass, null);
    }

    public static <S> S createService(Class<S> serviceClass, final String authToken) {  
      if (authToken != null) {
          builder.setRequestInterceptor(new RequestInterceptor() {
              @Override
              public void intercept(RequestFacade request) {
                  request.addHeader("Authorization", authToken);
              }
          });
      }

      RestAdapter adapter = builder.build();
      return adapter.create(serviceClass);
    }
}

As you can see, we pass the authentication token as a String variable into the method, use the Interceptor (RequestInterceptor in Retrofit 1) to set the HTTP header field for Authorization. In case you’re using another HTTP header field for your authentication token, either adjust the code above or create a new method which handles the desired functionality.

That’s it :)

From now on, every HTTP client created with this method integrates the token value for the Authorization header field and automatically passes the token value to your API endpoint with any request.

Example Usage

Let’s create an example and see some code. The UserService interface below declares a method called me(). This example method returns a user object created from API response.

Retrofit 2

public interface UserService {  
    @POST("/me")
    Call<User> me();
}

Retrofit 1.9

public interface UserService {  
    @POST("/me")
    User me();
}

The API you’re going to call awaits any requests at endpoint http://your.api-base.url/me and requires authentication to get user data in response. Now, let’s create a user service object and do the actual request

Retrofit 2

UserService userService =  
    ServiceGenerator.create(UserService.class, "auth-token");
Call<User> call = userService.me();  
User user = call.execute().body();  

Retrofit 1.9

UserService userService =  
    ServiceGenerator.create(UserService.class, "auth-token");
User user = userService.me();  

This code just illustrates how to use the presented classes. Of course, you have to pass your actual authentication token values to the ServiceGenerator method.

Have fun coding and using Retrofit for API authentication. If you run into questions or problems, just contact us via @futurestud_io.


Explore the Library

Find interesting tutorials and solutions for your problems.