token_manager_dio 0.2.1
token_manager_dio: ^0.2.1 copied to clipboard
Single-flight OAuth/JWT refresh for Dio: attaches the access token, refreshes once on 401 and replays the request.
token_manager_dio #
Dio refresh token interceptor: attach the bearer token, refresh once on 401 and retry the request — the
Dio adapter for token_manager.
One interceptor attaches the access token, recognises an auth failure and replays the request once.
It depends only on the core and dio, and never refreshes by itself: the manager owns the refresh.
Contents #
- Install
- Should I use this?
- Quick start
- How a request flows
- The delegate
- Errors
- Limitations
- Migration from 0.1
- Recipes
- Reference
Install #
dependencies:
token_manager: ^0.2.0
token_manager_dio: ^0.2.0
Should I use this? #
- Use it when: the app has an access token and a refresh token, several requests can run at once, and a 401 must trigger exactly one refresh.
- You do not need it when: the API uses a long-lived static key, or the app never refreshes tokens.
- What it replaces: a hand-written Dio interceptor that refreshes in
onError. That code tends to refresh once per failed request (N parallel 401s cause N refreshes) and to loop when the refresh itself fails. Here the manager keeps one refresh in flight, a request is replayed at most once, and a failed refresh reaches the caller as a typed error. - Which package:
| You use | Package |
|---|---|
| Any Dart code, or a transport not listed here | token_manager |
dio |
token_manager_dio (this package) |
package:http |
token_manager_http |
grpc |
token_manager_grpc |
GraphQL (gql_link) |
token_manager_gql |
Every adapter needs the core, so install token_manager too.
Quick start #
import 'package:dio/dio.dart';
import 'package:token_manager/token_manager.dart';
import 'package:token_manager_dio/token_manager_dio.dart';
// Says how the tokens reach the request.
final class BearerDelegate extends RefreshInterceptorDelegate<TokenSet> {
const BearerDelegate();
@override
void applyTo(RequestOptions options, TokenSet tokens) {
options.headers['Authorization'] = 'Bearer ${tokens.accessToken}';
}
}
void configureClient(Dio dio, TokenManager<TokenSet> manager) {
dio.interceptors.add(
DioTokenInterceptor<TokenSet>(
manager: manager,
delegate: const BearerDelegate(),
// The Dio the interceptor is added to: the replay keeps its adapter,
// its other interceptors and its timeouts.
dio: dio,
),
);
}
A complete runnable program is in example/main.dart.
How a request flows #
- Before sending — the interceptor asks
TokenManager.validToken(). Tokens close to expiry are refreshed first; concurrent requests share one refresh. - Header — the delegate's
applyTowrites the tokens into the request, and the interceptor remembers which tokens the request was sent with. - Auth failure — when
shouldRefreshaccepts the response (status 401 by default), the interceptor callsvalidToken(rejected: ...)with the tokens that were rejected. - Replay — the request is sent again once, on a copy marked as a replay, through the
dioyou passed. A marked request is never replayed again, so the interceptor cannot loop.
If the manager returns the very tokens that were rejected, it could not refresh: the original error reaches the caller and nothing is sent twice.
The delegate #
RefreshInterceptorDelegate<T> is the only part you write.
| Member | Purpose |
|---|---|
applyTo(options, tokens) |
Required. Writes the tokens into the request; tokens is never null. |
shouldRefresh(response) |
Whether a response is an auth failure worth a replay. Defaults to status 401. |
Override shouldRefresh for an API that signals expiry differently:
import 'package:dio/dio.dart';
import 'package:token_manager/token_manager.dart';
import 'package:token_manager_dio/token_manager_dio.dart';
final class ApiKeyDelegate extends RefreshInterceptorDelegate<TokenSet> {
const ApiKeyDelegate();
@override
void applyTo(RequestOptions options, TokenSet tokens) {
options.headers['X-Access-Token'] = tokens.accessToken;
}
@override
bool shouldRefresh(Response<Object?>? response) {
// This API also reports an expired token with a response header.
return response?.statusCode == 401 ||
response?.headers.value('X-Token-Expired') == 'true';
}
}
Errors #
The interceptor never swallows a failure to obtain or renew tokens. The DioException carries the cause
in error:
e.error |
Meaning |
|---|---|
NotAuthenticated |
There are no tokens: the user is logged out. Nothing was sent. |
InvalidGrant |
The refresh token was rejected for good; the manager signed the session out. |
Transient |
The refresh failed for a reason that may go away; the session is kept. |
On a refresh failure e.response is the 401 that started it. A replay the server rejects again reaches
you as the usual DioException of that second response.
Limitations #
- Streams — a
Streambody cannot be sent twice, so the original error is returned and no refresh is started. - Multipart — a
FormDatabody is cloned. A file part built from a one-shot stream (the deprecatedMultipartFile(stream, length)) is sent empty on the replay; useMultipartFile.fromFile,fromBytesorfromString. - Same-Dio loop guard — pass the
Diothe interceptor is added to. Withoutdio:the replay goes through a plainDio()that has none of your adapter, interceptors or timeouts. - Methods — any HTTP method is replayed; make sure a second attempt is safe for non-idempotent calls.
Migration from 0.1 #
RefreshInterceptor is now DioTokenInterceptor, applyTokensToRequest is now applyTo, and a few
failure paths changed. 0.1 code still compiles, with deprecation warnings.
doc/migration.md lists every change.
Recipes #
Each recipe is one page with complete code that is compiled and tested in this repository.
Reference #
- doc/getting_started.md — wiring a manager, a delegate and a
Dio. - doc/migration.md — upgrading from 0.1.
token_manager— the core: storage, single-flight refresh, errors.- CHANGELOG
Generate API docs: cd packages/token_manager_dio && dart doc .