Retrofit Basic Authentication in Android App with OkHttp

Carvia Tech | August 03, 2019 | 2 min read | 199 views


Retrofit (v2.6.1) and OkHttp (v4.0.1) are open source rest-client libraries for Android. You can use these libraries in your project to easily consume your web APIs.

Today we are going to learn how to add basic authentication in your app with the retrofit.

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

It’s really simple you just need to do is add an authentication interceptor in your OkHttp client.

You just need to create a Request interceptor(BasicAuthInterceptor) which extends Interceptor class of OkHttp library. Then, override intercept function and add your credentials into the request. Generate basic credentials with Credentials class of package OkHttp by using its basic function. Pass username and password to basic function as function arguments and it will return base64 encoded string. Use this string with Authorization header.

Let’s code it.

BasicAuthInterceptor.kt
class BasicAuthInterceptor(username: String, password: String): Interceptor {
    private var credentials: String = Credentials.basic(username, password)

    override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
        var request = chain.request()
        request = request.newBuilder().header("Authorization", credentials).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.

Inject interceptor into OkHttpClient
val client =  OkHttpClient.Builder()
    .addInterceptor(BasicAuthInterceptor(Username, Password))
    .build()

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

Complete Solution

class BasicAuthInterceptor(username: String, password: String): Interceptor {
    private var credentials: String = Credentials.basic(username, password)

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

        return chain.proceed(request)
    }
}

class BasicAuthClient<T> {
    private val client =  OkHttpClient.Builder()
            .addInterceptor(BasicAuthInterceptor("<username>", "<password>"))
            .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()}")
                }
            }
        })
    }
}

Creating a Basic Auth server using Spring Boot 2

If you are interested in creating a simple REST API secured by Basic Auth, this spring boot 2 based project will be helpful:


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



Find more on this topic:
Mobile Programming image
Mobile Programming

Android and iOS/Swift Programming Tutorials, Interview questions and recipes.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info