Auth tokens and interceptors

Learn how to use OkHttp interceptors and authenticators in Android with Kotlin to handle 401 errors and thread-safe token refreshes using a Mutex. About 25 minutes.

Why it matters

  • A stale token is a common cause of 401 storms in production; the interceptor + authenticator pair is the standard fix on OkHttp.
  • Interviewers ask you to draw the call order: application interceptors, then OkHttp's retry-and-follow-up step (which calls the Authenticator on 401), then network interceptors and the socket. Getting it wrong makes auth bugs hard to debug.
  • Without a lock, concurrent calls that all get a 401 fire several refresh requests. With rotating refresh tokens, the first refresh invalidates the old refresh token and the others fail, logging the user out.
  • A logging interceptor that prints the Authorization header in a release build is a real security incident.

The simple explanation

  • Your phone wallet holds a transit card (access token) that expires periodically.
  • A guard at the gate (interceptor) shows the card for you before you enter.
  • If the card is rejected, the guard calls the transit office (Authenticator) to get a new card.
  • While the office is printing, everyone else with a rejected card waits in line, then uses the new card instead of asking for another one (synchronized refresh with a re-check).
  • If the office says "account closed" (refresh rejected), everyone is sent home (log out).
  • You never write the card number on a sticky note (never log tokens).

Application interceptors (addInterceptor) run once per call and are the right place to add the Authorization header. Network interceptors (addNetworkInterceptor) run once per network request, so a redirect or retry runs them again.

When the server returns 401 Unauthorized, OkHttp's retry-and-follow-up step calls the Authenticator set with OkHttpClient.Builder.authenticator(...). authenticate(route, response) returns a new Request to retry, or null to give up and deliver the 401 to the caller. The retried request does not pass through application interceptors again, so the authenticator must put the new header on it itself.

If several calls get a 401 at the same time, OkHttp calls authenticate once for each, on OkHttp's own threads. authenticate is a blocking function, so guard the refresh with synchronized, and inside the lock compare the token on the failed request with the stored token: if they differ, another thread already refreshed and you just retry with the stored token. In coroutine code (a suspend refresh in a repository, or your own Ktor setup) the same single-flight idea uses a Mutex.

LayerRunsSeesTypical use
Application interceptorOnce per callThe request your code built, the final responseAdd Authorization, logging
Network interceptorOnce per network requestHeaders OkHttp adds, the connectionObserving traffic, network stats
AuthenticatorOn each 401 responseThe 401 response and its requestRefresh the token, rebuild the request

Give up instead of looping: return null when the request has already been retried after a 401 (response.priorResponse), and send the refresh request through a client that does not have this authenticator. If the refresh endpoint rejects the refresh token, clear the session and send the user to login. If the refresh fails because of the network, fail the call but keep the session.

Store tokens encrypted with a key held in the Android Keystore (for example Tink with DataStore). EncryptedSharedPreferences still works but the Jetpack Security Crypto library is deprecated. Never print a token in any log.

A 401, one refresh, one retry
A 401, one refresh, one retry The app's request goes through the application interceptor, which adds the Authorization header, and on to the server. The server answers 401. OkHttp calls the Authenticator, which gets a new access token from the token endpoint and returns a copy of the request with the new header. OkHttp retries it, skipping the application interceptors, and the server answers 200. The retry skips app interceptors REQUEST + HEADER SEND 401 UNAUTHORIZED authenticate() REFRESH NEW TOKEN SAME REQUEST RETRY 200 OK Interceptor adds the header OkHttp call engine Authenticator on 401 API server resource Token API refresh endpoint
The retried request does not pass through the application interceptors again, so the Authenticator must put the new token on it itself.

Notes

  • An application interceptor is added with addInterceptor(...) and runs once per call. A network interceptor is added with addNetworkInterceptor(...) and runs once per network request, including redirects and retries.
  • The Authenticator is set with OkHttpClient.Builder.authenticator(...). Its signature is authenticate(route: Route?, response: Response): Request?; the failed request is response.request.
  • Inside synchronized, re-read the stored token. If it differs from the token on the failed request, retry with the stored token without refreshing.
  • Return null when response.priorResponse is already a 401, so a call is retried at most once. Without a limit, OkHttp keeps following up until its limit of 20 follow-ups.
  • Make the refresh call with a client that has no TokenAuthenticator (for example the base client before you add auth), so a 401 from the refresh endpoint cannot call the authenticator again.
  • Keep the current access token in memory (a @Volatile field or a StateFlow) so the interceptor reads it cheaply on OkHttp threads, and persist it encrypted for the next launch.
  • Refresh rejected (400 or 401 from the token endpoint): clear tokens and emit a logout event. Refresh failed (no network, 5xx): return null for this call but keep the session.
  • HttpLoggingInterceptor belongs only in debug builds; call redactHeader("Authorization") so even debug logs do not show tokens.
  • Only attach the token to your own API host. One shared OkHttpClient (and clients derived with newBuilder()) for the whole app.
  • synchronized in an Authenticator is fine: it blocks an OkHttp thread, not a coroutine dispatcher. In suspend code, use Mutex.withLock instead.

Code example

This shows an application interceptor that attaches the token, and an Authenticator that refreshes once under a lock, re-checks the stored token, limits retries, and logs out only when the refresh token is rejected.

import okhttp3.Authenticator
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
 
interface TokenStore {
    val accessToken: String?  // kept in memory, persisted encrypted
    val refreshToken: String?
    fun save(access: String, refresh: String)
    fun clear()               // also emits a logout event
}
 
sealed interface RefreshResult {
    data class Success(val access: String, val refresh: String) : RefreshResult
    data object Rejected : RefreshResult // refresh token expired or revoked
    data object Failed : RefreshResult   // network error or 5xx
}
 
fun interface TokenRefresher {
    // Blocking call through a client WITHOUT TokenAuthenticator, e.g. Retrofit Call.execute()
    fun refresh(refreshToken: String): RefreshResult
}
 
class AuthInterceptor(private val tokens: TokenStore) : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val token = tokens.accessToken ?: return chain.proceed(chain.request())
        val request = chain.request().newBuilder()
            .header("Authorization", "Bearer $token")
            .build()
        return chain.proceed(request)
    }
}
 
class TokenAuthenticator(
    private val tokens: TokenStore,
    private val refresher: TokenRefresher,
) : Authenticator {
    private val lock = Any()
 
    override fun authenticate(route: Route?, response: Response): Request? {
        // Already retried once after a 401: give up instead of looping.
        if (response.priorResponse?.code == 401) return null
 
        val failedToken = response.request.header("Authorization")?.removePrefix("Bearer ")
 
        synchronized(lock) {
            val current = tokens.accessToken
            // Another thread refreshed while we waited: retry with its token.
            if (current != null && current != failedToken) return response.request.withToken(current)
 
            val refreshToken = tokens.refreshToken ?: return null
            return when (val result = refresher.refresh(refreshToken)) {
                is RefreshResult.Success -> {
                    tokens.save(result.access, result.refresh)
                    response.request.withToken(result.access)
                }
                RefreshResult.Rejected -> {
                    tokens.clear() // log out
                    null
                }
                RefreshResult.Failed -> null // this call fails, the session stays
            }
        }
    }
 
    private fun Request.withToken(token: String): Request =
        newBuilder().header("Authorization", "Bearer $token").build()
}
 
// The base client is also used for the refresh call, so it has no authenticator.
val baseClient: OkHttpClient = OkHttpClient.Builder().build()
 
fun authClient(tokens: TokenStore, refresher: TokenRefresher): OkHttpClient =
    baseClient.newBuilder() // shares the connection pool
        .addInterceptor(AuthInterceptor(tokens))
        .authenticator(TokenAuthenticator(tokens, refresher))
        .build()
  • synchronized is an inline function, so return inside it returns from authenticate.
  • The re-check (current != failedToken) is what turns N concurrent 401s into one refresh call; the lock alone would only run N refreshes one after another.
  • RefreshResult.Failed does not clear tokens, so a user who goes offline is not logged out.

Run the idea in plain Kotlin

Five coroutines send an expired token at the same time. A Mutex plus a re-check of the stored token makes exactly one refresh call, the same single-flight idea the Authenticator uses with synchronized.

import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock

class TokenStore {
  @Volatile var accessToken = "token-1"
}

class Refresher(private val store: TokenStore) {
  private val mutex = Mutex()
  var refreshCalls = 0

  suspend fun freshToken(failedToken: String): String = mutex.withLock {
      if (store.accessToken != failedToken) {
          store.accessToken // another coroutine already refreshed
      } else {
          refreshCalls++
          delay(50) // call to the refresh endpoint
          store.accessToken = "token-" + (refreshCalls + 1)
          store.accessToken
      }
  }
}

fun main() = runBlocking {
  val store = TokenStore()
  val refresher = Refresher(store)
  val valid = "token-2" // the server has rotated keys, token-1 is expired

  suspend fun call(id: Int): String {
      val sent = store.accessToken
      delay(10) // request goes out
      if (sent == valid) return "call " + id + ": 200"
      val fresh = refresher.freshToken(sent)
      delay(10) // retried request
      val code = if (fresh == valid) 200 else 401
      return "call " + id + ": 401 -> retried with " + fresh + " -> " + code
  }

  val results = (1..5).map { id -> async { call(id) } }.awaitAll()
  results.forEach { println(it) }
  println("refresh calls: " + refresher.refreshCalls)
  println(call(6))
}

Expected output:

call 1: 401 -> retried with token-2 -> 200
call 2: 401 -> retried with token-2 -> 200
call 3: 401 -> retried with token-2 -> 200
call 4: 401 -> retried with token-2 -> 200
call 5: 401 -> retried with token-2 -> 200
refresh calls: 1
call 6: 200

In production

401 storm on app cold start
  • After the backend shortened access token lifetime, many cold starts briefly showed the login screen, and dashboards showed several refresh-endpoint calls per launch.
  • On launch, the home screen fired several Retrofit calls in parallel with an expired token, and each 401 ran its own refresh because the authenticator had no lock.
  • The backend rotates refresh tokens, so the first refresh invalidated the old refresh token and the other refreshes were rejected, which cleared the session.
The fix
  • Put the refresh inside synchronized in the Authenticator, and inside the lock compared the failed request's token with the stored one, retrying with the stored token when another thread had already refreshed.
  • Logged out only when the refresh endpoint rejected the refresh token, not on network errors.
  • Added a MockWebServer test that fires 5 concurrent calls with an expired token and asserts exactly one request to the refresh endpoint.
Token leaked through logs
  • HttpLoggingInterceptor at Level.HEADERS was added to the shared client without a debug check.
  • In release builds it printed the Authorization header to logcat, and the crash-reporting SDK attached recent log lines as breadcrumbs, sending tokens to a third-party dashboard.
  • The security team found it in an audit.
The fix
  • Added the logging interceptor only when BuildConfig.DEBUG is true, and called redactHeader("Authorization") and redactHeader("Cookie") on it.
  • Revoked the exposed sessions on the backend.
  • Added a release-build test that checks the shared client's interceptors do not include HttpLoggingInterceptor.

Common mistakes

  • No lock around token refresh. N concurrent 401s fire N refresh calls. With rotating refresh tokens, all but the first are rejected and the user is logged out. Use synchronized in the Authenticator or Mutex in suspend code.
  • A lock without a re-check. If each thread refreshes after acquiring the lock, you still get N refreshes, just one after another. Compare the failed token with the stored token first.
  • No retry limit. Returning a new request on every 401 loops until OkHttp's follow-up limit. Return null when response.priorResponse is already a 401.
  • Refreshing through the same client. If the refresh request goes through the client with the Authenticator, a 401 from the refresh endpoint calls the authenticator again. Use a client without it.
  • Logging the Authorization header. Even debug logs end up in bug reports and crash tools. Add HttpLoggingInterceptor only in debug and redact Authorization.
  • Storing tokens in plain SharedPreferences. Anyone with root, a debuggable build or a backup copy can read them. Encrypt with a Keystore-backed key and exclude the token file from backups.
  • Logging out on any refresh failure. A timeout on the refresh call is not an expired session. Log out only when the token endpoint rejects the refresh token.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“Where do you add the Authorization header in OkHttp, and why not in a network interceptor?”

“What happens when 20 concurrent calls all get a 401?”

“How do you handle the case where the refresh token itself is expired?”

“Where should the refresh token be stored, and why?”

Quiz

Which interceptor layer should add the Authorization header?

15 concurrent calls receive a 401. Which Authenticator design sends exactly one refresh request?

What should happen when the refresh endpoint rejects the refresh token with 401?

Where should the refresh token be stored on Android?

0 of 4 answered

Mini task

15-minute exercise: add a guarded token refresh to an existing OkHttp client

  1. Find your project's OkHttpClient (or create one in a Hilt @Module). Confirm there is one shared base client.

  2. Add an AuthInterceptor that reads the access token from an in-memory TokenStore and sets Authorization: Bearer <token> on requests to your API host.

  3. Implement a TokenAuthenticator that: returns null if response.priorResponse?.code == 401; inside synchronized, retries with the stored token if it differs from the failed one; otherwise refreshes through the base client (without the authenticator), saves the new tokens and returns the request with the new header.

  4. On a rejected refresh, clear the tokens and emit a logout event; on a network failure, return null without clearing.

  5. Register the interceptor with addInterceptor(...) and the authenticator with authenticator(...) on baseClient.newBuilder().

  6. Write a test with MockWebServer: return 401 for the old token and 200 for the new one, fire 5 concurrent calls, and assert the refresh endpoint was called exactly once.

  7. Add HttpLoggingInterceptor only when BuildConfig.DEBUG is true, with redactHeader("Authorization").

Done condition: the test passes with one refresh call for five concurrent 401s, a rejected refresh logs the user out, and grep -r "Bearer" app/src/main finds no hardcoded token strings.

Next: Caching and offline reads