niharika2810 / MovieTray

Its a playground application focusing on Paging3, MVVM architecture, Kotlin Extension functions, Retrofit, DSL, Navigation component, MotionLayout, SharedElementTransition, Single Activity Architecture, DataStore etc.
100 stars 19 forks source link

How to pass Auth bearer token Hilt DI? #1

Open Neerav006 opened 3 years ago

Neerav006 commented 3 years ago

Hello , This is not issue , I'm new to mvvm structure, How to pass Auth bearer token in NetworkModule from token stored in Preference. Give some solution would be nice.

saitej-janjirala commented 2 years ago

@Neerav006 you can create a custom interceptor for your HttpBuilder in that you can add like this.

val httpClientBuilder = OkHttpClient.Builder().apply {

                    addInterceptor(object :Interceptor{
                        override fun intercept(chain: Interceptor.Chain): Response {
                            val originalRequest = chain.request()

                            val newRequest = originalRequest.newBuilder().apply {

                                headers(Headers.Builder().apply {
                                    addAll(originalRequest.headers)
                                    val token = AppPreferences.getAccessToken()?.accessToken
                                    if(token != null) {
                                        add("Authorization", token)
                                        if(BuildConfig.DEBUG){
                                            Log.i("Authorization", "token : $token")
                                        }
                                    }
                                }.build())
                            }.build()
                            return chain.proceed(newRequest)
                        }

                    })
                }

tempInstance = Retrofit.Builder().baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(httpClientBuilder.build()) .build()