HTTP
Other HTTP clients
Use Authyra with package:http, Chopper, gRPC or anything else.
Every client integration is the same three steps, built on accessToken():
- Before the request, get a token for a session and remember both.
- On a 401, ask for a new token for that session, passing the rejected token.
- Retry once with it.
nullmeans the session ended: give up.
package:http
import 'package:authyra/authyra.dart';
import 'package:http/http.dart' as http;
class AuthyraClient extends http.BaseClient {
AuthyraClient(this.authyra, [http.Client? inner]) : _inner = inner ?? http.Client();
final Authyra authyra;
final http.Client _inner;
@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
final key = authyra.currentSession?.key;
final token = await authyra.accessToken(key: key);
final response = await _inner.send(_withToken(request, token));
if (response.statusCode != 401 || token == null) return response;
final renewed = await authyra.accessToken(key: key, rejectedToken: token);
if (renewed == null) return response; // The session ended.
await response.stream.drain<void>();
return _inner.send(_withToken(request, renewed));
}
http.BaseRequest _withToken(http.BaseRequest original, String? token) {
// A request can only be sent once: copy it for the retry.
final copy = http.Request(original.method, original.url)
..headers.addAll(original.headers)
..followRedirects = original.followRedirects;
if (original is http.Request) copy.bodyBytes = original.bodyBytes;
if (token != null) copy.headers['Authorization'] = 'Bearer $token';
return copy;
}
}
This sketch handles http.Request bodies only; streamed and multipart requests need their own copy logic.
The rules that matter
- Pass the session key you used for the first attempt. Without it, a 401 that arrives after the user switched accounts could be retried with the other account's token.
- Pass
rejectedToken. It lets Authyra skip the refresh when another request already replaced that token. - Retry once. If the new token is rejected too, the problem is not the token.
- Never refresh yourself. Go through
accessToken(), so all callers share one refresh.