Authenticating with OkHttp interceptors

Although we're using a base authentication security, we need a username and password to grant access to this REST API. Here, we're using OkHttp interceptors for authentication. This will help you to send a request and get the auth permission to access the resources.

Here, we've called the BasicAuthInterceptor class in OkHttpClient.Builder():

 private fun getOkhttpClient(username:String, password:String): OkHttpClient{
return OkHttpClient.Builder()
.addInterceptor(BasicAuthInterceptor(username, password))
.build()
}

Here's the class of BasicAuthInterceptor.kt:

class BasicAuthInterceptor(user: String, password: String) : Interceptor {

private val credentials: String = Credentials.basic(user, password)

@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val authenticatedRequest = request.newBuilder()
.header("Authorization", credentials).build()
return chain.proceed(authenticatedRequest)
}
}

In this class, only the credentials are added as your user details. Here, a client will make a request using the username and password credentials. During every request, this interceptor acts before it's performed and alters the request header. Consequently, you don't need to add @HEADER("Authorization") to the API function.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.44.182