In a Retrofit app, how do you add a bearer token to every request through the OkHttpClient, and why not use @Header on each method?
answer
- one place, not every method
- Interceptor wraps chain.proceed
- newBuilder on the request
- header replaces, addHeader appends
- application slot, before the logger
basics
~20 sWrite an OkHttp Interceptor that reads the current token, copies the request with newBuilder().header("Authorization", "Bearer ..."), and calls chain.proceed; add it to the one OkHttpClient given to Retrofit, so no service method has to carry the token.
solid answer
~40 sI add an application interceptor to the single `OkHttpClient` passed to `Retrofit.Builder.client()`. In `intercept`, it takes `chain.request()`, reads the current access token from an in-memory store, and calls `chain.proceed(request.newBuilder().header("Authorization", "Bearer $token").build())`; `header()` replaces any existing value where `addHeader()` would add a second one. A `@Header` parameter on every method would force each caller to pass the token, is easy to forget, and puts an auth concern into the API interface, while `@Headers` only takes constants. The interceptor runs on the thread executing the call, which for suspend and `enqueue` calls is an OkHttp dispatcher thread, so a quick synchronous read is fine but a network refresh is not. Endpoints such as login get a client built without it, or a per-method opt-out.
code
kotlin · 17 linesimport okhttp3.Interceptor
import okhttp3.Response
interface TokenStore {
val accessToken: String?
}
class AuthHeaderInterceptor(private val tokens: TokenStore) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val token = tokens.accessToken ?: return chain.proceed(request)
val authorized = request.newBuilder()
.header("Authorization", "Bearer $token") // replaces, never duplicates
.build()
return chain.proceed(authorized)
}
}go deeper
Know that a header every call needs belongs in an OkHttp interceptor on the client given to Retrofit, not in each service method.
Explain the intercept steps, why header() beats addHeader() for Authorization, and which thread the interceptor runs on for suspend and enqueue calls.
Show where the header does not travel: the Authenticator's retry and cross-host redirects. Keep login and refresh calls off the authenticated client without a second pool.
Set one way the app attaches credentials, so new modules cannot invent their own, and decide which endpoints are allowed to opt out.
## Why an interceptor rather than @Header Retrofit can put a header on a request in three ways, and only one of them suits a credential that every call needs. | Approach | How it works | Problem for a bearer token | |---|---|---| | `@Header("Authorization") token: String` | a parameter on each service method | every caller must fetch and pass the token; one missed method ships unauthenticated | | `@Headers("...")` | a constant on the method or interface | the value is fixed at compile time, so a token cannot go there | | OkHttp `Interceptor` | code on the client that rewrites each request | neither problem; this is where Retrofit's own documentation sends headers needed on every request | An interceptor keeps the service interface about the API (paths, queries, bodies) and keeps authentication in one place that can change without touching any call site. ## Writing the interceptor An OkHttp `Interceptor` has one method, `intercept(chain: Interceptor.Chain): Response`. An auth-header interceptor does five things: 1. Takes the request Retrofit built with `chain.request()`; the `@Path`, `@Query` and `@Header` values are already in it. 2. Reads the current access token from a store, ideally an in-memory value that a refresh updates. 3. If there is no token (the user is signed out), calls `chain.proceed(request)` unchanged. 4. Otherwise builds a copy with `request.newBuilder().header("Authorization", "Bearer $token").build()`. `Request.Builder.header()` **replaces** every existing header of that name; `addHeader()` would **append** a second `Authorization` line if one were already there. 5. Returns `chain.proceed(newRequest)`. The interceptor runs on whichever thread executes the call. For Retrofit's `suspend` methods and for `Call.enqueue`, that is a background thread from OkHttp's dispatcher; for `Call.execute()` it is the caller's thread. A quick synchronous read of a cached token is therefore fine, but the interceptor should not perform a network refresh on every request. ## One client, passed to Retrofit - Build the `OkHttpClient` once, typically as a singleton in the dependency graph, and pass it to `Retrofit.Builder.client()`. Each `OkHttpClient` built from scratch owns its own connection pool and thread pools, so creating one per screen or per call wastes both. - When some endpoints must not carry the token, such as login or the token-refresh call itself, derive a second client with `newBuilder()` from a base client that has no auth interceptor and give it to a second `Retrofit` instance. `newBuilder()` shares the pool and threads; note that it also copies the interceptors the source client already has. - The alternative is a per-method opt-out: a custom annotation on the service method, read in the interceptor from the `Invocation` tag Retrofit attaches to every request. ## Which slot it occupies - Add it with `addInterceptor`, the **application** slot. There it runs once per call, even when OkHttp follows a redirect or retries. - Add it **before** `HttpLoggingInterceptor`, so the logger, which runs after it, prints the header (redacted). - It does **not** run again for an `Authenticator`'s retry after a 401: that follow-up request goes through OkHttp's internal chain, so the `Authenticator` must put the new token on the request it returns. - When OkHttp follows a redirect to a different host, port or scheme, it removes `Authorization` from the follow-up, and an application interceptor does not get a chance to put it back. That is deliberate: credentials should not travel to another origin. ## What does not belong in it - Reacting to a 401. That is the `Authenticator`'s job, because OkHttp calls it exactly when a server rejects the credentials. - Long blocking work on every request, such as a locked disk read, which every call would pay for. - Single-flight refresh and proactive refresh before expiry, which are request-pipeline design rather than how this client is composed. ## Common mistakes - **Capturing the token when the client is built.** An interceptor constructed with a `String` keeps sending that value after a refresh or sign-out; it must read the store on every call. - **Using `addHeader()`.** If anything upstream already set `Authorization`, the request carries two values and the server may reject it. - **Building a new `OkHttpClient` after every login** to bake in the new token, which throws away the warm connection pool each time. - **Sending the token to every host.** When the same client also fetches third-party URLs, check `request.url.host` before attaching the header.
- Your auth interceptor adds the token, yet a request that was redirected to a CDN host arrives without it; is that a bug?No. When OkHttp follows a redirect to a different host, port or scheme, it removes `Authorization` from the follow-up request, and an application interceptor runs only once per call, so it cannot re-add it. That keeps credentials from leaking to another origin; a CDN URL should carry its own signed access, not the user's bearer token.
- How do you keep the login and refresh endpoints from receiving a stale bearer token?Either give those endpoints their own Retrofit instance on a client derived with `newBuilder()` from a base client that lacks the auth interceptor, or mark the service methods with a custom annotation and have the interceptor skip them after reading the method from Retrofit's `Invocation` tag. Both keep one shared connection pool.
- Put @Header("Authorization") on every service method and pass the token from each caller.
- @Headers can hold the bearer token if you build the interface after login.
- addHeader and header behave the same for Authorization.
- Interceptors run on the main thread because the UI started the call.
- The auth interceptor also re-adds the token to the Authenticator's 401 retry.
- Create a new OkHttpClient per screen so each gets the latest token.