Skip to main content

token_manager_http 0.1.2 copy "token_manager_http: ^0.1.2" to clipboard
token_manager_http: ^0.1.2 copied to clipboard

Single-flight OAuth/JWT refresh for package:http: a Client that attaches the access token, refreshes once on 401 and replays the request.

token_manager_http #

Pub Version Dart Transport Part of

An http client with bearer token authorization and refresh on 401 — the package:http adapter for token_manager: HttpTokenClient, a BaseClient that wraps your Client, attaches the manager's tokens to every request that passes shouldAuthorize, refreshes once when the server rejects them and replays the request. It depends only on http and token_manager.

Contents #

Install #

dependencies:
  http: ^1.5.0
  token_manager: ^0.2.0
  token_manager_http: ^0.1.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 package:http Client wrapper that adds the header and retries after a 401. 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
package:http token_manager_http (this package)
grpc token_manager_grpc
GraphQL (gql_link) token_manager_gql

Every adapter needs the core, so install token_manager too.

Quick start #

import 'package:http/http.dart';
import 'package:token_manager/token_manager.dart';
import 'package:token_manager_http/token_manager_http.dart';

Future<String> fetchProfile(TokenManager<TokenSet> manager) async {
  final client = HttpTokenClient<TokenSet>(manager: manager, inner: Client());
  try {
    final response = await client.get(Uri.parse('https://api.example.com/me'));
    return response.body;
  } finally {
    client.close();
  }
}

The client never refreshes by itself: it asks the manager for valid tokens (which refreshes them first when they are about to expire) and reports the tokens a server rejected. Concurrent requests share one refresh. Every authorized request is sent as a copy, so your request object never gets the token header. A runnable version without a network is in example/main.dart.

doc/getting_started.md

What is replayed #

Every row passes shouldAuthorize; a request that fails it is sent unchanged, without tokens, and never replayed.

Request Replayed after a rejection
Request: everything get, post, put, patch, delete, head send once
AbortableRequest once, with its abort trigger
StreamedRequest, MultipartRequest, their abortable variants, other subclasses no
  • The rejected body is read first. Before a replay the client reads the 401 to the end, so its connection is released. A 401 that is not replayed still reaches you with its body.
  • A request that cannot be replayed is sent once and its 401 is returned as is. The client reports the rejected tokens, so the next request gets new ones.
  • One replay, never a loop. When the replay is rejected too, that response is returned.

doc/replay.md

Requests without tokens #

A login or sign-up runs before tokens exist. Exclude it with shouldAuthorize, and it is sent unchanged without asking the manager:

final client = HttpTokenClient<TokenSet>(
  manager: manager,
  inner: Client(),
  shouldAuthorize: (request) => request.url.path != '/oauth/token',
);

Without it, a request sent while signed out fails with NotAuthenticated.

Headers and auth failures #

Option Default
headers Authorization: Bearer <accessToken> for TokenSet; required for any other token type
isAuthFailure status 401
shouldAuthorize every request
final client = HttpTokenClient<MyTokens>(
  manager: manager,
  inner: Client(),
  headers: (tokens) => {'X-Api-Key': tokens.apiKey},
  isAuthFailure: (response) => {401, 419}.contains(response.statusCode),
);

The token header replaces a header with the same name on the request, in any letter case.

Errors #

Thrown by send, get, ... Meaning
NotAuthenticated no session; nothing more is sent
InvalidGrant the session ended and the manager signed out
Transient the refresh may succeed later; the session stays
ClientException a network error, or a request after close()

The manager's failures are not wrapped. Listen to manager.states to send the user to sign-in on Unauthenticated.

Closing #

close() closes the inner client exactly once. It does not dispose the manager: the client does not own it, and several clients may share one manager. Dispose the manager yourself when the session ends.

Testing #

Pass a MockClient from package:http/testing.dart as inner and an InMemoryTokenStore to the manager; nothing touches the network. doc/testing.md

Dependency constraints #

http ^1.5.0: 1.5.0 added AbortableRequest and AbortableStreamedRequest, which the client uses to keep the abort trigger of a request on the copy it sends.

Recipes #

Each recipe is one page with complete code that is compiled and tested in this repository.

Reference #

0
likes
160
points
36
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Single-flight OAuth/JWT refresh for package:http: a Client that attaches the access token, refreshes once on 401 and replays the request.

Homepage
Repository (GitHub)
View/report issues
Contributing

Topics

#http #authentication #oauth #refresh-token #jwt

License

MIT (license)

Dependencies

http, token_manager

More

Packages that depend on token_manager_http