Skip to main content

axiom_flutter_auth 0.150.0 copy "axiom_flutter_auth: ^0.150.0" to clipboard
axiom_flutter_auth: ^0.150.0 copied to clipboard

Managed Axiom project authentication for Flutter: sign-in, token refresh with rotation, secure session storage, PKCE redirects and MFA, wired into axiom_flutter.

axiom_flutter_auth #

Managed Axiom project authentication for Flutter. It is the Dart port of @axiomcore/auth-web (auth-surfaces/v1): the same concepts and method names, on Android, iOS, macOS and web. It also plugs into axiom_flutter, so every Axiom call carries a fresh access token.

Install #

flutter pub add axiom_flutter:^0.150.0 axiom_flutter_auth:^0.150.0

Both packages are released together with the same version number.

Quickstart #

import 'package:axiom_flutter/axiom_flutter.dart';
import 'package:axiom_flutter_auth/axiom_flutter_auth.dart';

final auth = createAxiomAuth(AxiomAuthOptions(
  issuer: 'https://<project>.axiomcore.dev/...',   // [auth.environments.<env>].issuer
  redirectUri: 'com.example.app:/auth/callback',  // listed in redirect_urls
  storage: platformStorage(),                     // Keychain/Keystore; sessionStorage on web
));

Future<void> main() async {
  final sdk = await AxiomSdk.create();            // generated by `axiom pull`
  AxiomAuthBinding.attach(auth, runtime: sdk.runtime, namespaces: ['api']);
  await auth.restore();                           // authenticated | anonymous | expired | error
  runApp(AxiomAuthLifecycle(auth: auth, child: MaterialApp(
    home: AxiomAuthBuilder(
      auth: auth,
      loading: (_, __) => const CircularProgressIndicator(),
      signedOut: (_, __) => SignInPage(onSubmit: auth.signInWithPassword),
      signedIn: (_, s) => HomePage(subject: s.principal!.subject),
    ),
  )));
}

Errors are AxiomAuthError with code (invalid_credentials, mfa_required, unavailable, ...), status (HTTP, or 0 for client-side and network failures) and retryAfterSeconds. A message never contains a token or a ticket.

What it does #

auth-web Dart Notes
createAxiomAuth(options) createAxiomAuth(AxiomAuthOptions) / AxiomAuth(...) createAxiomAuth also installs the flutter_web_auth_2 launcher.
session(), subscribe() same, plus sessionListenable (ValueListenable<PublicSession>) and AxiomAuthBuilder The principal object is reused while its content is unchanged.
restore(), refresh({tenant}), selectTenant same Refresh is single-flight, with a proactive timer and jitter. It rotates the refresh token, backs off on unavailable/rate_limited (honours Retry-After) and ends the session on invalid_refresh (reuse detection).
signUp, verifySignUp, signInWithPassword, requestEmailCode, verifyEmailCode same
requestMagicLink, signInWithProvider, signInHosted, handleRedirect same PKCE S256. The provider and hosted flows open the system browser and return the session instead of navigating away.
signOut({everywhere, redirect, returnTo}) same Drops the credentials and the stored record first, then revokes on the issuer (/v1/logout or /v1/logout-all).
authorizationHeader(), authorizedFetch authorizationHeader(), accessToken(), authorizedClient() / authorizedSend() Sends the bearer only to apiOrigins (and to the page origin on web). On 401 authorization_changed it refreshes once and retries once.
mfaChallenge, verifyMfa, verifyRecoveryCode, sendSmsCode, stepUp, listFactors, enrollTotp, confirmTotp, removeFactor, regenerateRecoveryCodes, phone, consents same The sealed ticket stays private. It expires after 300 s.
passkeys (signInWithPasskey, verifyMfaWithPasskey, registerPasskey) same, through an AxiomPasskeys you supply Flutter has no built-in WebAuthn. Plug in any passkeys plugin (WebAuthn JSON in and out). Without one, these fail with webauthn.
parseStepUpChallenge, runtimeAuthRefusal same
visibilitychange setForeground(bool), or wrap the app in AxiomAuthLifecycle

Wiring into axiom_flutter #

AxiomAuthBinding.attach(auth, runtime: ..., namespaces: ['api']) does three things, for the listed namespaces only:

  • It pushes every new access token with setNamespaceAuthToken for each listed namespace, and clears exactly those on sign-out. On a runtime without that setter it falls back to setAuthToken for each method you list in authMethods: {'api': ['method']} (keys must be listed namespaces).
  • It answers setAuthProvider with auth.accessToken() for the listed namespaces and with null for any other namespace.
  • On sign-out it calls resetSession(), which clears the session-partitioned cache and cancels in-flight calls.

namespaces is required and has no "all" value. List only the namespaces whose backend accepts tokens from this issuer (normally your own API). A vendor or public contract loaded next to it (cms on cms.vendor.io) must not be listed: it would receive the user's bearer token. The binding never calls setGlobalAuthToken; a global token reaches every loaded namespace, so set one yourself only when every contract the app loads trusts it.

Token storage #

The storage adapter holds only the refresh record. The access token stays in memory.

Adapter Where Trade-off
memoryStorage() (default) process memory Nothing touches disk. The user signs in again after a restart (or a reload on web).
secureStorage() flutter_secure_storage 10: iOS/macOS Keychain (first_unlock_this_device), Android Keystore-backed ciphers The recommended choice on mobile and desktop. On macOS see the two keychain modes below.
sessionStorageAdapter() web window.sessionStorage (per tab, survives a reload) Same trade-off as auth-web: any script on the page (XSS) can read the refresh token. Use it only with a strict Content-Security-Policy. Otherwise keep memoryStorage(). Do not use secureStorage() on web: it encrypts with a key kept beside the data in localStorage.
platformStorage() sessionStorageAdapter() on web, secureStorage() elsewhere Takes the same macOsDataProtectionKeychain option.

You can also implement AuthStorageAdapter (get/set/remove) yourself.

macOS keychain modes #

Mode How Requirements
Legacy login keychain (default) secureStorage() / platformStorage() None. Works in unsigned, ad-hoc signed and flutter run builds. Do not add keychain-access-groups to the entitlements for this mode.
Data-protection keychain secureStorage(macOsDataProtectionKeychain: true) A team-signed app with the Keychain Sharing capability (Xcode > Signing & Capabilities > Keychain Sharing, which adds keychain-access-groups).

Do not ship the keychain-access-groups entitlement in an app that is not signed with a development team: macOS kills such an app at launch, before any Dart code runs. Records written in one mode are not visible in the other, so pick one before release.

When the platform store is unavailable #

secureStorage() never throws at start-up because of the platform store. If a keychain or keystore call fails (no keychain, missing plugin, missing entitlement such as -34018), the adapter prints one warning and keeps the session in memory for the rest of the process, so the user stays signed in until the app quits. adapter.usingMemoryFallback tells you this happened. Pass fallbackToMemory: false to get the platform error instead.

Platform requirements #

  • Android: minSdk = 23 and compileSdk = 36 in android/app/build.gradle.kts (required by flutter_secure_storage 10). Gradle also suggests ndkVersion = "27.0.12077973".
  • Web with dart2wasm (flutter build web --wasm) works: flutter_secure_storage 10's web part uses package:web, not dart:html. Version 9 broke wasm builds of any app using this package.
  • Upgrading from flutter_secure_storage 9 on Android: v10 migrates entries stored with encryptedSharedPreferences to its own ciphers on first access.

The default launcher is FlutterWebAuth2Launcher (flutter_web_auth_2). It uses ASWebAuthenticationSession on iOS/macOS, Custom Tabs on Android and a popup on web. Add redirectUri to the environment's redirect_urls.

  • Android: add the callback activity for your scheme to AndroidManifest.xml (see example/android/app/src/main/AndroidManifest.xml): com.linusu.flutter_web_auth_2.CallbackActivity with an intent filter for <data android:scheme="com.example.app" />.
  • iOS/macOS: nothing to add for a custom scheme.
  • Web: the popup's callback page must post its URL back to the opener (flutter_web_auth_2's auth.html). As an alternative, use a full-page redirect: write a launcher that assigns location, then call auth.restore() on load. The PKCE verifier must survive the reload for this to work, so the in-memory transaction store only covers the popup flow.
  • Magic links and password-reset links arrive through your app-link handler. Pass the URL to auth.handleRedirect(uri).

Testing against the local emulator #

axiom auth emulate is a loopback issuer. It supports sign-up with mail codes, password, email code, refresh rotation with reuse detection, logout, /v1/user and provider sign-in through a mock OIDC issuer. It does not support MFA, step-up, hosted /sign-in or magic links. Those are covered by test/mfa_test.dart against a scripted issuer.

flutter test                                # unit tests; the emulator tests skip
AXIOM_SQLITE_LIBRARY=/path/libsqlite3.so tool/emulator.sh   # 9 emulator tests
AXIOM_SQLITE_LIBRARY=/path/libsqlite3.so tool/web_smoke.sh  # headless Chrome: sign-in, reload, restore, sign-out

The emulator needs SQLite 3.44 or newer, and Debian 12 ships 3.40. To get a newer one, build the amalgamation with gcc -O2 -fPIC -shared sqlite3.c -o libsqlite3.so.0. On a machine that is not registered with Axiom Cloud, the scripts set a loopback AXIOM_CLOUD_URL; the emulator itself makes no cloud call.

Developing this package #

The published pubspec depends on axiom_flutter: ^0.150.0. To work against the axiom_flutter sources in this repository, create a pubspec_overrides.yaml next to pubspec.yaml (it is git-ignored and listed in .pubignore, so it is never committed or published):

dependency_overrides:
  axiom_flutter:
    path: ../axiom_flutter

Then run flutter pub get. dart pub publish --dry-run ignores the override and validates the version constraint. The example app in example/ carries its own dependency_overrides and needs nothing extra.

0
likes
140
points
107
downloads

Documentation

Documentation
API reference

Publisher

verified publisheryashmakan.com

Weekly Downloads

Managed Axiom project authentication for Flutter: sign-in, token refresh with rotation, secure session storage, PKCE redirects and MFA, wired into axiom_flutter.

Repository (GitHub)
View/report issues

Topics

#authentication #oauth #security #api

License

MIT (license)

Dependencies

axiom_flutter, crypto, flutter, flutter_secure_storage, flutter_web_auth_2, http, web

More

Packages that depend on axiom_flutter_auth