Retrofit2 Authorization - Global Interceptor for access token

前端 未结 5 1343
我在风中等你
我在风中等你 2020-12-22 23:24

I\'m trying to use Retrofit2, I want to add Token to my Header Like this:

Authorization: Bearer Token but the <

5条回答
  •  清酒与你
    2020-12-23 00:06

    You will need to add an Interceptor into the OkHttpClient.

    Add a class called OAuthInterceptor.

    class OAuthInterceptor(private val tokenType: String, private val accessToken: String) : Interceptor {
        override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
            var request = chain.request()
            request = request.newBuilder().header("Authorization", "$tokenType $accessToken").build()
    
            return chain.proceed(request)
        }
    }
    

    Following that, when you initialise your RetrofitApiService interface, you will need this.

    interface RetrofitApiService {
        companion object {
            private const val BASE_URL = "https://api.coursera.org/api/businesses.v1/"
            fun create(accessToken: String): RetrofitApiService {
                val client = OkHttpClient.Builder()
                        .addInterceptor(OAuthInterceptor("Bearer", accessToken))
                        .build()
    
                val retrofit = Retrofit.Builder()
                        .addConverterFactory(GsonConverterFactory.create())
                        .baseUrl(BASE_URL)
                        .client(client)
                        .build()
    
                return retrofit.create(RetrofitApiService::class.java)
            }
        }
    }
    

    Shout out to Java Code Monk, and visit the reference link for more details. https://www.javacodemonk.com/retrofit-oauth2-authentication-okhttp-android-3b702350

提交回复
热议问题