authyra_dio 0.3.0
authyra_dio: ^0.3.0 copied to clipboard
Dio interceptor for Authyra: attaches a fresh access token to each request, and on a 401 refreshes once for all concurrent requests, then retries.
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.
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
DioExceptionwhoseerroris aTokenRefreshException; 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
Dioyour provider uses for/auth/loginand/auth/refreshmust not carry this interceptor: a refresh call that triggers a refresh cannot finish. Use a separate instance.
License #
MIT