Login Diagram
Interceptor
- Retrofit uses Okhttp through which we can add interceptors to our retrofit client.
- Retrofit triggers the Interceptor instance whenever a request is made.
- With the interceptor we can add the token in every request.
Kotlin
class AuthorizationInterceptor : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val requestBuilder = chain.request().newBuilder()
// If token has been saved, add it to the request
sessionManager?.fetchAuthToken()?.let {
requestBuilder.addHeader("Authorization", it)
return chain.proceed(requestBuilder.build())
}
}
SessionManager
- The session manager will help us to save, fetch, or delete the token in the
SharedPreferences
ServiceBuilder
- We create a builder of the retrofit object which can be reused for all method calls declared in the RestApi interface
Kotlin
object ServiceBuilder {
private val client =
OkHttpClient.Builder().addInterceptor(AuthorizationInterceptor()).build()
private val retrofit = Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL) // change this IP for testing by your actual machine IP
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
fun <T> buildService(service: Class<T>): T {
return retrofit.create(service)
}
}