authyra_dio

A Dio interceptor for Authyra: it attaches a valid access token to each request and, on a 401, refreshes once for all concurrent requests, then retries them.

Documentation ยท Live demo

Install

dart pub add authyra_dio

Usage

import 'package:authyra_dio/authyra_dio.dart';
import 'package:dio/dio.dart';

final api = Dio(BaseOptions(baseUrl: 'https://api.example.com'));
api.interceptors.add(
  AuthyraInterceptor(
    authyra: authyra,
    dio: api,
    // Never send your tokens to another host.
    shouldAttach: (request) => request.uri.host == 'api.example.com',
  ),
);

Behavior

  • Before each request: asks Authyra for a valid token, refreshing first if it is about to expire.
  • On a 401: refreshes that request's session, passing the rejected token, and retries once. Twenty concurrent 401s cause one refresh call.
  • Refresh token rejected: the session ends and the original 401 is passed on.
  • Refresh failed for a temporary reason: the session is kept. Before sending with an expired token, the request fails with a DioException whose error is a TokenRefreshException; after a 401, the original 401 is passed on.

Each request remembers the session it was sent for, so an account switch in the middle never mixes tokens.

Per request:

// Public endpoint: no token, no refresh.
await api.get('/health', options: Options(extra: {AuthyraInterceptor.skip: true}));

// On behalf of an account that is not the active one.
await api.get('/me', options: Options(extra: {AuthyraInterceptor.sessionKey: key}));

The Dio your provider uses for /auth/login and /auth/refresh must not carry this interceptor: a refresh call that triggers a refresh cannot finish. Use a separate instance.

License

MIT

Libraries

authyra_dio
Dio integration for Authyra.