Getting started

Quick start

Sign in against your own API, keep the session fresh and send authenticated requests.

This page wires a Flutter app to a typical backend: POST /auth/login and POST /auth/refresh return an access token, a refresh token and expires_in.

Install

flutter pub add authyra_flutter authyra_dio dio

Describe how to talk to your backend

A provider holds no state: it turns credentials into tokens, and a refresh token into new tokens. Throw RefreshRevokedException when the server rejects the refresh token; any other error is treated as temporary.

lib/auth.dart
import 'package:authyra_flutter/authyra_flutter.dart';
import 'package:dio/dio.dart';

/// A separate client for auth calls, without the Authyra interceptor.
final authApi = Dio(BaseOptions(baseUrl: 'https://api.example.com'));

AuthTokens tokensFrom(Map<String, dynamic> json) => AuthTokens.expiringIn(
  Duration(seconds: json['expires_in'] as int),
  accessToken: json['access_token'] as String,
  refreshToken: json['refresh_token'] as String?,
);

final apiProvider = CredentialsProvider(
  id: 'api',
  signIn: (credentials) async {
    try {
      final response = await authApi.post<Map<String, dynamic>>(
        '/auth/login',
        data: {'email': credentials.identifier, 'password': credentials.password},
      );
      final user = response.data!['user'] as Map<String, dynamic>;
      return AuthSignInResult(
        user: AuthUser(id: user['id'] as String, email: user['email'] as String?),
        tokens: tokensFrom(response.data!),
      );
    } on DioException catch (error) {
      if (error.response?.statusCode == 401) return null; // Wrong credentials.
      rethrow;
    }
  },
  refresh: (refreshToken) async {
    try {
      final response = await authApi.post<Map<String, dynamic>>(
        '/auth/refresh',
        data: {'refresh_token': refreshToken},
      );
      return tokensFrom(response.data!);
    } on DioException catch (error) {
      if (error.response?.statusCode == 401) {
        throw const RefreshRevokedException();
      }
      rethrow; // Network, timeout, 5xx: Authyra keeps the session and retries.
    }
  },
);

Start Authyra

initialize restores the sessions saved on the device, then keeps the active one fresh. AuthyraScope makes it available to widgets and refreshes when the app comes back to the foreground.

lib/main.dart
Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  final authyra = await Authyra.initialize(
    storage: SecureAuthStorage(),
    providers: [apiProvider],
  );
  runApp(AuthyraScope(authyra: authyra, child: const App()));
}

Show the right screen

lib/app.dart
class App extends StatelessWidget {
  const App({super.key});

  @override
  Widget build(BuildContext context) => MaterialApp(
    home: AuthStateBuilder(
      builder: (context, state) => switch (state) {
        AuthUnknown() => const SplashScreen(),
        AuthSignedIn(:final user) => HomeScreen(user: user),
        AuthSignedOut() => const SignInScreen(),
      },
    ),
  );
}

Signing in and out from a screen:

final authyra = AuthyraScope.of(context);

await authyra.signIn(
  'api',
  params: CredentialsSignInParams(identifier: email, password: password),
);

await authyra.signOut();

Send authenticated requests

AuthyraInterceptor attaches a valid token to each request and recovers from a 401 with one shared refresh.

final api = Dio(BaseOptions(baseUrl: 'https://api.example.com'));
api.interceptors.add(AuthyraInterceptor(authyra: authyra, dio: api));

final orders = await api.get<List<Object?>>('/orders');

What you get

  • The session survives restarts, in the platform keystore.
  • The access token is refreshed 60 seconds before it expires, and when your API answers 401.
  • Twenty concurrent 401s cause one refresh, not twenty.
  • An offline period or a server error never signs the user out; a rejected refresh token does.
  • Without a refresh callback, the session ends when the access token expires or your API answers 401.
See it happen in the Session Lab, then read How it works.
Copyright © 2026