Concepts
How it works
The roles of providers, Authyra, storage and your HTTP client, and what happens from sign-in to sign-out.
Four roles
Your UI ──── reads ────▶ AuthState (AuthUnknown | AuthSignedIn | AuthSignedOut)
│ ▲
│ signIn / signOut │ publishes
▼ │
Authyra ── owns ──▶ sessions, refresh scheduling, multi-account, events
│ │
│ └── persists ──▶ AuthStorage (platform keystore)
│
└── asks ──▶ AuthProvider (your API, OAuth server, Google, Apple...)
Your HTTP client ── accessToken() ──▶ Authyra
| Role | Responsibility | Holds state? |
|---|---|---|
| Provider | Authenticates the user, renews tokens, revokes them on sign-out. | No. It returns results; it never stores a session. |
| Authyra | Builds the session, persists it, refreshes it, ends it, publishes the state. | Yes, the single owner of every session. |
| Storage | Keeps sessions across restarts. | Only strings under authyra.* keys. |
| HTTP client | Asks for a token before each request, reports a 401. | No. authyra_dio does this for Dio. |
Because providers are stateless, you can change how users sign in without touching how sessions behave, and test each side on its own.
The life of a session
- Sign-in.
authyra.signIn('api', params: ...)calls the provider, which returns anAuthSignInResult: the user, the tokens, and optional provider data. Authyra builds anAuthSession, persists it, makes it active and emitsAuthSignedIn. - Use. Your HTTP client calls
authyra.accessToken()before each request. A valid token is returned at once; a token about to expire is refreshed first. - Proactive refresh. While the app runs, the active session is refreshed shortly before its access token expires (60 seconds by default), so requests rarely wait.
- Recovery. When your API answers 401 anyway, the client asks for a new token with
rejectedToken. If another caller already refreshed, the new token is returned without a second refresh. - Failures. A refresh that fails for a transient reason (network, timeout, 5xx) keeps the session and is retried with backoff. A refresh token the server rejects ends the session: Authyra emits
SessionEndedEventwithSessionEndReason.revoked, and the state becomesAuthSignedOutif no other account remains. - Sign-out.
authyra.signOut()blocks new refreshes, waits for one in flight, asks the provider to revoke the latest tokens server-side, then removes the session. - Restart. At the next launch,
start()restores every session. A session whose access token expired while the app was closed is refreshed; one that can no longer be renewed is discarded.
One instance, or several
Authyra.initialize(...) creates an app-wide instance reachable through Authyra.instance. When you inject dependencies yourself, create one with the constructor and call start():
final authyra = Authyra(storage: SecureAuthStorage(), providers: [apiProvider]);
await authyra.start();
dispose() stops background work and waits for writes in progress. Sessions stay persisted.