JWT Login on Android with Automatic Refresh Tokens (OkHttp Authenticator)
Quick answer: Use a short-lived access token and a long-lived refresh token. An interceptor adds the access token to every request; when the API answers 401, an OkHttp Authenticator calls the refresh endpoint once (synchronized, so parallel requests don't refresh at the same time), saves the new tokens and retries the original request. If the refresh fails, clear the tokens and send the user to login.
Short-lived access tokens are safer: if one leaks, it expires in minutes. But nobody wants to log in again every 15 minutes. The solution is a refresh token and an automatic renewal flow. This guide builds it on Android with Retrofit and OkHttp, avoiding the mistakes that cause logout loops and duplicate refreshes.
Why use refresh tokens?
- The access token can expire quickly (5 to 30 minutes), limiting damage if it leaks;
- The user stays logged in for days or weeks;
- The server can revoke a refresh token (logout, stolen phone, password change);
- Each refresh can rotate the refresh token, so a stolen one stops working.
The authentication flow
- The user logs in; the API returns
access_tokenandrefresh_token; - The app sends the access token in every request;
- When it expires, the API returns 401;
- The app calls
POST /auth/refreshwith the refresh token; - The API returns new tokens; the app saves them and repeats the original request;
- If the refresh is rejected, the app clears everything and shows the login screen.
1. The response model
import com.google.gson.annotations.SerializedName
data class AuthResponse(
@SerializedName("access_token") val accessToken: String,
@SerializedName("refresh_token") val refreshToken: String,
@SerializedName("expires_in") val expiresIn: Int
)
data class RefreshRequest(
@SerializedName("refresh_token") val refreshToken: String
)
2. Storing the tokens
import android.content.Context
class TokenStore(context: Context) {
private val prefs = context.getSharedPreferences("auth", Context.MODE_PRIVATE)
val accessToken: String? get() = prefs.getString("access", null)
val refreshToken: String? get() = prefs.getString("refresh", null)
fun save(access: String, refresh: String) {
prefs.edit().putString("access", access).putString("refresh", refresh).apply()
}
fun clear() = prefs.edit().clear().apply()
}
App-private storage is only readable by your app on a normal device. For extra protection, encrypt the values with a key from the Android Keystore. Note that the Jetpack Security library (EncryptedSharedPreferences) has been deprecated, so avoid starting new code on it. Also exclude the token file from cloud backups (android:dataExtractionRules), so tokens aren't restored on another device.
3. The interceptor that adds the header
import okhttp3.Interceptor
import okhttp3.Response
class AuthInterceptor(private val store: TokenStore) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val token = store.accessToken ?: return chain.proceed(chain.request())
return chain.proceed(
chain.request().newBuilder()
.header("Authorization", "Bearer $token")
.build()
)
}
}
4. The Authenticator that refreshes on 401
OkHttp has a component made exactly for this: an Authenticator is called automatically when a response is 401, and whatever request it returns is retried. It is cleaner than checking 401 inside an interceptor.
import okhttp3.Authenticator
import okhttp3.Request
import okhttp3.Response
import okhttp3.Route
class TokenAuthenticator(
private val store: TokenStore,
private val authApi: AuthApi, // a separate Retrofit service, WITHOUT this authenticator
private val onLogout: () -> Unit
) : Authenticator {
override fun authenticate(route: Route?, response: Response): Request? {
// Already retried once with a refreshed token: give up to avoid an infinite loop
if (response.priorResponse != null) return null
val failedToken = response.request.header("Authorization")?.removePrefix("Bearer ")
synchronized(this) {
val current = store.accessToken
// Another request already refreshed while we were waiting: just retry with it
if (current != null && current != failedToken) {
return response.request.newBuilder()
.header("Authorization", "Bearer $current")
.build()
}
val refresh = store.refreshToken ?: run { onLogout(); return null }
val result = try {
authApi.refresh(RefreshRequest(refresh)).execute()
} catch (e: Exception) {
return null // network error: let the call fail, don't log the user out
}
val body = result.body()
if (!result.isSuccessful || body == null) {
store.clear()
onLogout()
return null
}
store.save(body.accessToken, body.refreshToken)
return response.request.newBuilder()
.header("Authorization", "Bearer ${body.accessToken}")
.build()
}
}
}
Three details matter here:
- Synchronized refresh: when five requests fail with 401 at once, only the first one refreshes; the others see the new token and retry with it. Without this, the server receives five refreshes, and with token rotation four of them fail and log the user out;
- No infinite loop:
priorResponsetells you this request was already retried; - Network errors aren't logouts: only a rejected refresh token should end the session.
5. A separate service for the refresh call
The refresh request must not go through the same authenticator, or a rejected refresh would trigger another refresh:
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST
interface AuthApi {
@POST("auth/refresh")
fun refresh(@Body body: RefreshRequest): Call<AuthResponse> // synchronous, called inside the Authenticator
}
6. Wiring it together
val authApi = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(OkHttpClient()) // plain client
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(AuthApi::class.java)
val client = OkHttpClient.Builder()
.addInterceptor(AuthInterceptor(store))
.authenticator(TokenAuthenticator(store, authApi) { sessionEvents.tryEmit(SessionExpired) })
.build()
val api = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiService::class.java)
onLogout runs on a background thread, so don't open a screen from it directly: emit an event (for example in a SharedFlow) that the UI collects and reacts to by showing the login screen.
7. The refresh endpoint on the server
On the backend, POST /auth/refresh should:
- check that the refresh token exists, isn't expired and isn't revoked (store a hash of it in the database);
- issue a new access token and a new refresh token, and invalidate the old one (rotation);
- if an already-used refresh token shows up again, revoke the whole session: it may have been stolen;
- answer 401 when the refresh is rejected.
For a PHP backend, see JWT authentication in PHP.
Best practices
- Access tokens of 5 to 30 minutes, refresh tokens of days or weeks;
- Rotate refresh tokens on every use;
- Revoke refresh tokens on logout and password change;
- Never log tokens, even in debug;
- Treat a failed refresh as the end of the session, but a network error as a temporary failure.
Conclusion
An interceptor for the header, an Authenticator for 401 responses and a synchronized refresh give you secure short-lived tokens without bothering users. Built this way, the flow handles parallel requests, avoids loops and only logs the user out when the session really ended. For the basics of the client, see consuming a REST API with Retrofit.
Frequently asked questions
Interceptor or Authenticator for refreshing tokens?
Use an interceptor to add the header and an Authenticator to handle 401. OkHttp calls the Authenticator only when authentication fails, and retries automatically.
Why does my app log out when several requests run at once?
Each request refreshed the token in parallel; with rotation, only the first refresh succeeds. Synchronize the refresh and reuse the new token, as above.
Can I call a suspend function inside the Authenticator?
The Authenticator is synchronous and already runs on a background thread, so use a synchronous Call with execute() for the refresh.
Where should I store JWTs on Android?
In app-private storage, optionally encrypted with a key from the Android Keystore, and excluded from backups.
How long should tokens last?
Typical values are 15 minutes for the access token and 7 to 30 days for the refresh token, depending on how sensitive the app is.