JWT authentication looks simple until your app fires five requests at once and the access token expires in the middle. Then you get five refresh calls, a refresh token that has been rotated out from under you, and a user who is randomly logged out. This article shows an approach that avoids those race conditions.
The model
- Access token: short-lived (minutes), sent with every request.
- Refresh token: long-lived, used only to get a new access token.
Store both in secure storage (flutter_secure_storage, which uses Keychain on iOS and encrypted storage on Android), never in SharedPreferences.
The problems to solve
- Attach the token to every request.
- When a request returns
401, refresh once, even if many requests failed at the same time. - Retry the original request with the new token.
- Never loop forever; if refresh fails, log the user out.
Use a queued interceptor and a separate Dio
Two details matter:
QueuedInterceptorprocesses errors one at a time, so concurrent401s wait their turn instead of all refreshing.- The refresh and retry calls use a separate Dio without interceptors. Calling the main Dio from inside a queued interceptor can deadlock, and it would re-trigger the same interceptor.
class AuthInterceptor extends QueuedInterceptor {
AuthInterceptor(this._tokens, this._plainDio, {required this.onSessionExpired});
final TokenStore _tokens;
final Dio _plainDio; // same baseUrl, NO interceptors
final void Function() onSessionExpired;
@override
Future<void> onRequest(RequestOptions options, RequestInterceptorHandler handler) async {
final token = await _tokens.access;
if (token != null) options.headers['Authorization'] = 'Bearer $token';
handler.next(options);
}
@override
Future<void> onError(DioException err, ErrorInterceptorHandler handler) async {
final is401 = err.response?.statusCode == 401;
final alreadyRetried = err.requestOptions.extra['retried'] == true;
if (!is401 || alreadyRetried) return handler.next(err);
try {
final sent = err.requestOptions.headers['Authorization'];
final current = await _tokens.access;
// Another queued request already refreshed: just retry with the new token.
if (current != null && sent != 'Bearer $current') {
return handler.resolve(await _retry(err.requestOptions, current));
}
final refreshToken = await _tokens.refresh;
if (refreshToken == null) throw StateError('No refresh token');
final res = await _plainDio.post('/auth/refresh', data: {'refreshToken': refreshToken});
final newAccess = res.data['accessToken'] as String;
await _tokens.save(access: newAccess, refresh: res.data['refreshToken'] as String);
handler.resolve(await _retry(err.requestOptions, newAccess));
} catch (_) {
await _tokens.clear();
onSessionExpired();
handler.next(err);
}
}
Future<Response<dynamic>> _retry(RequestOptions options, String token) {
options.headers['Authorization'] = 'Bearer $token';
options.extra['retried'] = true;
return _plainDio.fetch(options);
}
}
The check sent != 'Bearer $current' is the part most tutorials miss. When refresh tokens rotate, a second refresh with the old token fails, and that would log the user out even though a valid new token is already stored.
Handling logout
onSessionExpired should do exactly one thing: tell the app that the session ended (for example, emit an event on an AuthBloc that navigates to login). Do not navigate from inside the interceptor.
Proactive refresh
You can also check the exp claim before sending a request and refresh slightly early. It reduces visible 401s, but you still need the reactive path above, because clocks drift and tokens can be revoked server-side.
Security notes
- Keep access tokens short-lived; rotate refresh tokens and revoke them server-side on logout.
- Never log tokens. Disable body logging in release builds; see the network layer guide.
- Do not trust the client for authorization. The app hides buttons; the server enforces permissions.
- Clear the token store and any cached user data on logout.
Testing it
Test with a fake adapter: fire several requests that all return 401, then assert that the refresh endpoint was called once and that every request eventually succeeded. This is the test that catches the race condition; see testing Flutter apps.
Key takeaways
- Use
QueuedInterceptorso concurrent401s refresh once. - Use a separate plain Dio for refresh and retry to avoid loops and deadlocks.
- If the request's token is already outdated, retry with the stored one instead of refreshing again.
- On refresh failure, clear tokens and notify the app to log out.
I implemented JWT flows like this in production Flutter apps. Contact me if you need help with auth in yours.