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
- Getting Started and Creating an Android Client
- Basics of API Description
- Creating a Sustainable Android Client
- URL Handling, Resolution and Parsing
- How to Change API Base Url at Runtime
- Multiple Server Environments (Develop, Staging, Production)
- Share OkHttp Client and Converters between Retrofit Instances
- Upgrade Guide from 1.9
- Beyond Android: Retrofit for Java Projects
- How to use OkHttp 3 with Retrofit 1
- Synchronous and Asynchronous Requests
- Send Objects in Request Body
- Add Custom Request Header
- Manage Request Headers in OkHttp Interceptor
- Dynamic Request Headers with @HeaderMap
- Multiple Query Parameters of Same Name
- Optional Query Parameters
- Send Data Form-Urlencoded
- Send Data Form-Urlencoded Using FieldMap
- How to Add Query Parameters to Every Request
- Add Multiple Query Parameter With QueryMap
- How to Use Dynamic Urls for Requests
- Constant, Default and Logic Values for POST and PUT Requests
- Cancel Requests
- Reuse and Analyze Requests
- Optional Path Parameters
- How to Send Plain Text Request Body
- Customize Network Timeouts
- How to Trust Unsafe SSL certificates (Self-signed, Expired)
- Dynamic Endpoint-Dependent Interceptor Actions
- How to Update Objects on the Server (PUT vs. PATCH)
- How to Delete Objects on the Server
- Introduction to (Multiple) Converters
- Adding & Customizing the Gson Converter
- Implementing Custom Converters
- How to Integrate XML Converter
- Access Mapped Objects and Raw Response Payload
- Supporting JSON and XML Responses Concurrently
- Handling of Empty Server Responses with Custom Converter
- Send JSON Requests and Receive XML Responses (or vice versa)
- Unwrapping Envelope Responses with Custom Converter
- Wrapping Requests in Envelope with Custom Converter
- Define a Custom Response Converter
- Basic Authentication on Android
- Token Authentication on Android
- OAuth on Android
- Hawk Authentication on Android
- How to Refresh an Access Token
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.