Image credit: Maxime Bourgeois

Token-Based Authentication with Retrofit | Android OAuth 2.0

Vincent Kiptirgei
AndroidPub
Published in
3 min readFeb 15, 2020

--

Retrofit is a type-safe HTTP client by Square that was built for the Android platform. It offers an easy and clean way to make REST API network calls and parses the JSON/XML response(s) into Java Objects which we can then use in our app.

As a security measure, most API access points require users to provide an authentication token that can be used to verify the identity of the user making the request so as to grant them access to data/ resources from the backend. The client app usually fetches the token upon successful login or registration then saves the token locally and appends it to subsequent requests so that the server can authenticate the user.

In this blog we are going to see a clean way to append the logged in user’s token to our app API requests once the user has logged in. Our use case assumes the user needs to fetch a list of posts from the server.

Alright then, enough talk.. show me the code 🤨🤨

Setup Project

First we’ll proceed and create a new Android Studio project. For this project we’ll be using Kotlin however the same implementation works for Java.

Add the Retrofit dependencies to your app/build.gradle:

Then add the internet permission in your AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/>

Setup models

Let’s create the User.kt class that will contain the basic details of the User. For our use case it will only contain the user ID, first name, last name and email.

For login, the user will be required to provide the email and password so let’s create the LoginRequest.kt data class.

On successful login, the user will receive a response containing the status code, authentication token and user details. Let’s create the LoginResponse.kt.

Setup Retrofit

We will create a Constants.kt class that will hold our static variables.

Then we will create the ApiClient.kt class that will initialize our Retrofit client instance and the ApiService.kt interface where we will define our API request functions.

Fetching the token

In order to be able to save and fetch the token on the user’s device, we will create a SessionManager.kt class.

On successful login, we will save the fetched token.

Wheew! Our user can finally login, let’s take a five.

Adding the token to our requests

Now that our user can login, we can finally fetch a list of posts. Let’s first create a sample Post.kt object.

And the corresponding PostsResponse.kt data class.

In order to fetch the list of posts, we can add the authorization token as a header to the function to fetch posts then pass it as a parameter:

This should work quite well and we should be able to fetch the list of posts. However using this method means for each and every authenticated request we will have to add the Header parameter and pass the token from the function making the request. Not clean, is it?

Using a request Interceptor

Fortunately, Retrofit uses Okhttp through which we can add interceptors to our retrofit client. Retrofit triggers the Interceptor instance whenever a request is made.

Let’s go ahead and make an AuthInterceptor.kt for our requests so that we can add the token to the request.

We will then update our ApiClient.kt to include the custom Okhttp client.

Then we can remove the header parameter from our request function and from the function making the request then just call the request functions directly. For the unauthenticated endpoints such as login, the token value from Session Manager will be null thus will not be added to the request.

Conclusion

Retrofit is one of the best HTTP request android libraries and by decoupling the function to add the token to our request header, we are able to make our code cleaner and more maintainable.

You can find the whole code on GitHub:

Happy Coding :)

--

--

Vincent Kiptirgei
AndroidPub

Software Engineer | Open Source Enthusiast | Petrolhead