Retrofit OAuth2 Bearer Token Authentication OkHttp Android

Upasana | July 14, 2020 | 2 min read | 4,888 views


Retrofit (v2.5.0) and OkHttp (v3.14.0) are open source rest client libraries for Android. You can use these libraries in your project to easily consume your web APIs.

In this tutorial we are going to learn how to implement OAuth2(bearer Token) authentication in your app using the retrofit.

Please add Retrofit and OkHttp dependencies in you build.gradle file.
/app/build.gradle
    //Retrofit Libraries
    implementation 'com.squareup.retrofit2:retrofit:2.5.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
    //OkHttp Libraries
    implementation 'com.squareup.okhttp3:okhttp:3.14.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.14.0'

To add your Access Token in every authenticated request you need to add an authentication intercepter in your OkHttp client.

But Before this, You have to save(in SharedPrefrences or Other) OAuth2 login success response in order to extract Access token and other information later on.

Now you just need to create a request interceptor(OAuthIntercepter) which extends Interceptor class of OkHttp library. Then, override intercept function and add your Access Token into the request header. Extract Access Token and Use it with Authorization header.

Let’s code it.

class OAuthInterceptor(private val tokenType: String, private val acceessToken: String): Interceptor {

    override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
        var request = chain.request()
        request = request.newBuilder().header("Authorization", "$tokenType $acceessToken").build()

        return chain.proceed(request)
    }
}

We Are almost done, Now we just need to add this interceptor in your OkHttp Client and then add OkHttp Client in your retrofit instance.

val client =  OkHttpClient.Builder()
    .addInterceptor(OAuthInterceptor("Bearer", "---ACCESS---TOKEN---"))
    .build()

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com")
    .client(client)
    .build()

Complete Solution

class OAuthInterceptor(private val tokenType: String, private val acceessToken: String): Interceptor {

    override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
        var request = chain.request()
        request = request.newBuilder().header("Authorization", "$tokenType $acceessToken").build()

        return chain.proceed(request)
    }
}

class BasicAuthClient<T> {
    private val client =  OkHttpClient.Builder()
            .addInterceptor(OAuthInterceptor("Bearer", "---ACCESS---TOKEN---"))
            .build()

    val gson = GsonBuilder()
            .setLenient()
            .create()

    private val retrofit = Retrofit.Builder()
            .baseUrl("https://api.example.com")
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()

    fun create(service: Class<T>): T {
        return retrofit.create(service)
    }
}

interface DemoRemoteService {
    @GET("/profile")
    fun getProfile(): Call<Profile>
}

class Demo {
    fun loadProfile() {
        val call = BasicAuthClient<DemoRemoteService>().create(DemoRemoteService::class.java).getProfile()

        call.enqueue(object: Callback<Profile> {
            override fun onFailure(call: Call<Profile>, t: Throwable) {
                Log.e("DemoClass", t.message, t)
            }

            override fun onResponse(call: Call<Profile>, response: Response<Profile>) {
                if (response.isSuccessful) {
                    Log.i("DemoClass", "Profile Loaded.")
                } else {
                    Log.e("DemoClass", "Error: ${response.code()} ${response.message()}")
                }
            }
        })
    }
}

Top articles in this category:
  1. Retrofit Basic Authentication in Android
  2. Kotlin Coroutines with Retrofit
  3. Service vs Intent Service in Android
  4. Firebase Cloud Messaging in Android App using Command Pattern
  5. iOS interview questions for 0-3 years experience
  6. FirebaseInstanceIdService is deprecated now
  7. iOS interview experience fresher

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.