skip to content

With Retrofit on OkHttp, how does an Authenticator refresh an expired access token after a 401, and how do you stop it retrying forever?

level: seniorimportance: must knowfreq 68%

answer

  1. called only on a 401
  2. returns a Request or null
  3. priorResponse counts the attempts
  4. compare the sent token first
  5. refresh on a separate client

basics

~20 s

OkHttp calls the client's Authenticator when a server answers 401; it refreshes the token synchronously and returns the request with a new Authorization header, or returns null to hand the 401 back. Guard it with an attempt count and a token comparison.

solid answer

~50 s

`okhttp3.Authenticator` has one method, `authenticate(route, response): Request?`, set with `OkHttpClient.Builder.authenticator()`. OkHttp calls it only for a 401 from the origin server. I return `response.request.newBuilder().header("Authorization", "Bearer $new").build()` to retry, or `null` to give up, and then Retrofit sees the 401: a suspend method throws `HttpException`. To stop loops I count the `priorResponse` chain and give up after one retry; without a guard OkHttp only stops at its follow-up cap with a `ProtocolException`. Inside a `synchronized` block I compare the token the failed request carried with the stored one: if they differ, another call already refreshed, so I just retry. The refresh runs as a blocking `execute()` on a Retrofit service built on a client that has neither this Authenticator nor the auth interceptor, and the returned request must carry the header itself, because application interceptors do not run for the retry.

code

kotlin · 55 lines
kotlin
import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST

data class RefreshRequest(val refreshToken: String)
data class TokenPair(val accessToken: String, val refreshToken: String)

interface RefreshApi { // built on a client WITHOUT this authenticator or the auth interceptor
    @POST("auth/refresh")
    fun refresh(@Body body: RefreshRequest): Call<TokenPair>
}

interface TokenStore {
    val accessToken: String?
    val refreshToken: String?
    fun save(pair: TokenPair)
    fun clear()
}

class TokenAuthenticator(
    private val tokens: TokenStore,
    private val refreshApi: RefreshApi,
) : Authenticator {
    override fun authenticate(route: Route?, response: Response): Request? {
        if (response.responseCount >= 2) return null // already retried once: give up
        val sent = response.request.header("Authorization")?.removePrefix("Bearer ")
            ?: return null // no bearer token was sent (login, sign-up): nothing to refresh
        val token = synchronized(this) {
            val current = tokens.accessToken
            if (current != null && current != sent) {
                current // another call refreshed while this one waited
            } else {
                val refresh = tokens.refreshToken ?: return null
                val result = refreshApi.refresh(RefreshRequest(refresh)).execute()
                val pair = result.body()
                if (!result.isSuccessful || pair == null) {
                    tokens.clear()
                    return null // caller sees the 401
                }
                tokens.save(pair)
                pair.accessToken
            }
        }
        return response.request.newBuilder()
            .header("Authorization", "Bearer $token")
            .build()
    }

    private val Response.responseCount: Int
        get() = generateSequence(this) { it.priorResponse }.count()
}

go deeper

for a junior

Know that OkHttp's Authenticator is the hook called on a 401 and that it either returns a new request or null.

for a middle

Explain how a returned request becomes a follow-up, how null surfaces as an HttpException in Retrofit, and why the returned request must carry the header itself.

for a senior

Show a refresh that terminates: an attempt count from priorResponse, a lock with a sent-token comparison, a separate refresh client, and a clean sign-out path when the refresh fails.

for a principal

Weigh where token lifecycle logic lives across modules and how failures are reported, so one refresh bug cannot sign every user out at once.

## What an Authenticator is `okhttp3.Authenticator` is a single-method interface: - `authenticate(route: Route?, response: Response): Request?` receives the response that carried the challenge. `route` is best-effort and may be null. - It is installed with `OkHttpClient.Builder.authenticator()`. The default is `Authenticator.NONE`, which always returns null. - OkHttp calls it **only** when the origin server answers **401 Unauthorized**. A 407 from a proxy goes to the separate `proxyAuthenticator`, and a 403 never reaches either. What the method returns decides what happens next: | Return value | What OkHttp does | What the Retrofit caller sees | |---|---|---| | a `Request` with new credentials | sends it as a follow-up within the same call | the response to the retried request | | `null` | stops and returns the 401 | a suspend method returning `T` throws `HttpException` with code 401; `Response<T>` has `isSuccessful == false` | | the same rejected request, every time | keeps following up until its cap of 20 | a `ProtocolException`, "Too many follow-up requests: 21" | That last row is the loop the question is about. OkHttp's own documentation advises implementations to check whether the failed request already carried credentials, because further attempts with the same ones are unlikely to help. ## Writing a refresh that terminates 1. **Count the attempts.** Each follow-up links the previous response through `priorResponse`. Counting that chain, as OkHttp's recipes do with a `responseCount` extension, lets the Authenticator give up after one retry with fresh credentials. 2. **Serialise the refresh.** Several calls can fail with 401 at the same moment, each on its own OkHttp thread. A `synchronized` block lets one of them refresh while the others wait. 3. **Compare before refreshing.** Inside the lock, compare the token the failed request sent (`response.request.header("Authorization")`) with the one in the store. If they differ, another thread refreshed while this one waited: retry with the stored token and do not refresh again. 4. **Refresh synchronously.** `authenticate` runs on the thread executing the call, which for Retrofit's suspend methods and `enqueue` is an OkHttp dispatcher thread. A blocking `Call.execute()` is the expected tool here; there is no UI to touch. 5. **Use a separate client for the refresh call.** Build the refresh service on a client without this Authenticator and without the auth-header interceptor. Otherwise a 401 from the refresh endpoint re-enters the Authenticator on the same thread. 6. **Fail cleanly.** If the refresh itself is rejected, clear the stored tokens and return null, so the caller sees the 401 and the app can sign the user out. 7. **Set the header on the returned request.** The follow-up goes through OkHttp's internal chain and its network interceptors, not through application interceptors, so the auth-header interceptor does not run again. ## Edge cases worth knowing - **One-shot request bodies.** OkHttp still calls the Authenticator, but it will not resend a follow-up whose body is one-shot; the 401 goes back to the caller. - **Logging.** A logger in the application slot shows only the original request and the final response. A logger added as a network interceptor shows the 401 and the retry as separate exchanges. - **The refresh token's own lifetime.** When it has expired, step 6 applies; looping on refresh is the bug this design prevents. - **Scope of this lesson.** Making one refresh serve many queued calls across the whole app, refreshing proactively before expiry, and the OAuth refresh grant itself are covered with request-pipeline design and OAuth 2.0. Here the subject is the OkHttp hook a Retrofit client uses. ## Common mistakes - Returning `response.request` unchanged, which resends the rejected token until the follow-up cap ends the call. - Refreshing on a 401 from the **login** endpoint itself: a wrong password is not an expired token. Give login its own client, or skip the refresh when the failed request never carried a bearer token. - Launching the refresh asynchronously and returning before it finishes; `authenticate` must return the finished request. - Forgetting that `authenticate` may throw `IOException` when the refresh call itself fails on the network; the original call then fails with that exception. ## Why not refresh inside the auth-header interceptor? An application interceptor would have to inspect every response for 401, close it, refresh, and call `proceed` again, which re-implements what OkHttp already does in the right place. The Authenticator is invoked exactly when a challenge arrives, inside OkHttp's follow-up loop, with the failed response in hand and the follow-up limit already enforced. Keep the interceptor for attaching the current token and the Authenticator for replacing a rejected one.

  • After the Authenticator returns null, how does the 401 reach code that calls a Retrofit suspend method?
    OkHttp returns the 401 response as the call's result. Retrofit's suspend support sees a non-2xx response and throws `HttpException` carrying code 401; a method declared to return `Response<T>` instead gets a response whose `isSuccessful` is false. Either way the app can react, typically by signing the user out.
  • Why must the refresh request not go through the same OkHttpClient as the Authenticator?
    If the refresh endpoint answers 401, OkHttp would call the same Authenticator for that inner call, on the same thread that is already inside it, and the JVM lock is reentrant, so it would not even block. Building the refresh service on a client without the Authenticator and the auth-header interceptor keeps the refresh a plain call that simply fails.
  • Does a network interceptor see the Authenticator's retried request?
    Yes. The follow-up the Authenticator returns goes back through OkHttp's internal chain, including network interceptors, so a logger added with `addNetworkInterceptor` shows both the 401 exchange and the retry. Application interceptors, including a logger added with `addInterceptor`, see only the original request and the final response.

  • The Authenticator is also called for a 403 Forbidden.
  • Returning null from authenticate makes OkHttp retry the original request once.
  • The auth-header interceptor will put the new token on the retried request.
  • OkHttp never loops, so the Authenticator needs no attempt guard.
  • Use the same client for the refresh call so it gets logging and the auth header.
  • authenticate runs on the main thread, so the refresh must be launched in a coroutine.