Skip to main content

token_manager 0.2.0 copy "token_manager: ^0.2.0" to clipboard
token_manager: ^0.2.0 copied to clipboard

Token lifecycle management with storage, refresh, and token streams.

token_manager #

Pub Version Dart Dependencies Part of

The core of dart_token_manager — storage, single-flight refresh and an observable session state for authentication tokens. Pure Dart, no runtime dependencies, and it knows nothing about HTTP: the transport adapters (token_manager_dio, token_manager_grpc) plug into it.

Refresh is on demand. There is no background timer: tokens are refreshed when validToken, authorize or a rejected token asks for it.

Contents #

Install #

dependencies:
  token_manager: ^0.2.0

Quick start #

import 'package:token_manager/token_manager.dart';

final class MyRefresher implements TokenRefresher<TokenSet> {
  @override
  Future<TokenSet> refresh(TokenSet current) async {
    // Call your token endpoint with current.refreshToken.
    return TokenSet(
      accessToken: 'new-access',
      refreshToken: 'new-refresh',
      expiresAt: DateTime.now().add(const Duration(hours: 1)),
    );
  }
}

Future<void> main() async {
  final manager = TokenManager<TokenSet>.create(
    store: InMemoryTokenStore<TokenSet>(), // or a persistent TokenStore
    refresher: MyRefresher(),
    info: const TokenSetInfo(),
  );

  await manager.setTokens(
    TokenSet(
      accessToken: 'access',
      refreshToken: 'refresh',
      expiresAt: DateTime.now().add(const Duration(hours: 1)),
    ),
  );

  final tokens = await manager.validToken(); // refreshes when about to expire
  print(tokens.accessToken);
}

TokenSet is a ready-made token value; to use your own type T, implement TokenStore<T>, TokenRefresher<T> and TokenInfo<T>. A runnable version is in example/main.dart.

doc/getting_started.md walks through the setup step by step.

Session state #

manager.states replays the latest AuthState to every listener, then emits each change.

manager.states.listen((state) {
  switch (state) {
    case Unauthenticated():
      print('signed out');
    case Authenticated(:final tokens):
      print('signed in: ${tokens.accessToken}');
    case Refreshing():
      print('refreshing');
  }
});
State Meaning
Unauthenticated There are no tokens; the user is signed out.
Authenticated Signed in with the carried tokens.
Refreshing A refresh is running; the carried tokens are the ones being replaced.

doc/concepts.md explains how the state and the refresh fit together.

Authorizing calls #

authorize runs a call with valid tokens and replays it once when the server rejects them. authorizeStream does the same for streams, and never uses await for, so pause, resume and cancel reach the source.

final user = await manager.authorize(
  (tokens) => api.fetchUser(tokens.accessToken),
  isAuthFailure: (error) => error is ApiException && error.statusCode == 401,
);

final events = manager.authorizeStream(
  (tokens) => api.watchEvents(tokens.accessToken),
  isAuthFailure: (error) => error is ApiException && error.statusCode == 401,
);

validToken({rejected}) is the primitive underneath: concurrent callers share one refresh, and the tokens a server just rejected are refreshed unless another caller already replaced them.

doc/streams.md · doc/refreshing.md

Errors #

Thrown When
NotAuthenticated validToken or authorize ran without a session.
InvalidGrant The refresh token was rejected for good; the session ends and states emits Unauthenticated.
Transient The refresh failed for a reason that may go away; the session stays and the next call retries.

A TokenRefresher throws InvalidGrant or Transient; any other exception it throws is treated as transient. Storage failures are never reported as refresh failures.

doc/storage.md covers the failure semantics of the store.

Migrating from 0.1 #

The old API still works in 0.2, marked @Deprecated. See doc/migration.md.

Reference #

Guide Topic
Getting started Create a manager, sign in, read tokens, authorize a call
Concepts Layers, single-flight refresh, rejected-token compare, sessions
Storage TokenStore, InMemoryTokenStore, writing a secure-storage store
Refreshing TokenRefresher, TokenInfo and skew, failure types
Streams authorizeStream and its pause/resume/cancel contract
Testing Clock, fakes, how this package's tests are built
Migrating from 0.1 Mapping from the deprecated API

Generate API docs: cd packages/token_manager && dart doc .

0
likes
0
points
213
downloads

Publisher

unverified uploader

Weekly Downloads

Token lifecycle management with storage, refresh, and token streams.

Repository (GitHub)
View/report issues

License

unknown (license)

More

Packages that depend on token_manager