'How can I refresh jwt and request the original request again and get the response?

How can I handle 'refresh token' when 'access_token' is expired?

I know how it works. But what I want to know is implementing once and apply it to all the APIs.

When access token is expired, all the APIs are blocked(401) and need to request new token with refresh token.

So, I tried to do it within 'intercepter' because it can handle the request and response before sending or before handling in the application.

The process is like this.

  1. request an API

  2. catch the response

  3. if it's 401, call refresh token API

  4. get the response and request the original API that I was going to call.

  5. get the proper response from the original API.


// intercepter

val originalRequest = it.request()

val newRequestBuilder = originalRequest.newBuilder()

val response = it.proceed(newRequestBuilder.build())

if (response.code == 401) {

    // TODO: refresh token and request again and get the original response

}

response



Solution 1:[1]

Refresh tokens without getting "Error" response from API (Write only once)

I would suggest you to use Authenticator. OkHttp will automatically ask the Authenticator for credentials when a response is 401 Not Authorized retrying last failed request with them.

  1. Create a class MyAuthenticator and add the following code:

    class MyAuthenticator: Authenticator {
    
    
     override fun authenticate(route: Route?, response: Response): Request? {
    
         // set maixmum retry count
         if (response.responseCount >= 3) {
             return null // If we've failed 3 times, give up.
         }
    
    
        // write code to refresh the token
         val call = MyRetrofitClient.MyApi().refreshAccessToken()
         val res = call.execute()
         if (res.isSuccessful){
    
               val newAccessToken = res.body // your new token from response
               //
               response.request
                   .newBuilder()
                   .header("bearerToken", newAccessToken)
                   .build()
    
         }else{
             return null
         }
    
         return null
     }
    
     //
     private val Response.responseCount: Int
         get() = generateSequence(this) { it.priorResponse }.count()
    
    }
    
  2. Now you can attach this Authenticator to your OkHttpClient the same way you do with Interceptors

    private val client= OkHttpClient.Builder()
         .addInterceptor(MyInterceptor())
         .authenticator(MyAuthenticator()) // authenticator we created
         .build()
    
  3. Finally add this client to the Retrofit Builder:

    Retrofit.Builder()
             .baseUrl(BASE_URL)
             .client(client) // from 2nd step
             .build()
    

That's all, Now if 401 error occur, Authenticator will be called automatically and token will be refreshed and the pending API will be continued without getting error response.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jai Keerthick