Skip to content
Flutter SDK

Flutter authentication

Sign in with email or WhatsApp OTP, Google or Apple; persist and rotate sessions; link methods; sign out.

On this page

core.auth (AuthClient) signs users in, and core.session (SessionManager) holds the resulting session. Only offer methods listed in core.publicConfig.authMethods. Calling a disabled method throws a local FEATURE_UNAVAILABLE problem before any request is sent.

Method stringFlowStatus
email_otprequestOtp → verifyOtpFixture-tested. Real delivery needs an email sender connection on the backend; until then the server returns 503 FEATURE_UNAVAILABLE.
whatsapp_otprequestOtp → verifyOtpFixture-tested. The backend allows only allowlisted country codes, and real delivery needs a WhatsApp template.
googlesignInWithSocial(bridge)Fixture-tested with a fake bridge only. See the nonce warning below.
applesignInWithSocial(bridge)Fixture-tested with a fake bridge only. Native iOS flow only.
passkey—Not implemented (R3).

Endpoint details: Identity API.

Email or WhatsApp OTP

Dart
Future<void> signInWithEmail(AppCore core, String email, Future<String> Function() askForCode) async {
  if (!core.capabilities.auth('email_otp')) return;
  final challenge = await core.auth.requestOtp(method: 'email_otp', destination: email);
  // challenge.maskedDestination, challenge.resendAfter, challenge.expiresAt, challenge.deliveryStatus
  final code = await askForCode();
  final result = await core.auth.verifyOtp(challengeId: challenge.challengeId, code: code);
  print('signed in as ${result.user.id}');
}
  • requestOtp and verifyOtp are never retried automatically. A retry would send another message or use up an attempt. Each call carries a fresh Idempotency-Key.
  • verifyOtp rejects anything that is not exactly 6 digits with local INVALID_CODE_FORMAT, and does not call the server.
  • Use challenge.resendAfter for the resend cooldown. A 429 maps to NextAction.waitForCooldown, with retryAfterSeconds when the server sends it.
  • If deliveryStatus is unavailable, offer another method.
  • For WhatsApp, an unsupported country gets a 422 that lists the methods that are enabled.

The ready-made OtpSignInForm widget implements this flow.

Google and Apple (native)

The SDK does not import Google or Apple plugins. You pass a SocialSignInBridge:

Dart
abstract class SocialSignInBridge {
  String get provider; // 'google' | 'apple'
  Future<SocialCredential?> signIn({required String nonce}); // null = user cancelled
  Future<void> signOut();
}

signInWithSocial generates a random nonce and calls your bridge. It then posts provider, id_token, nonce (only when the bridge returns SocialCredential.rawNonce), authorization_code, and given_name / family_name when present, to POST /v1/auth/social. The server verifies the ID token against the provider's keys. The SDK never treats profile JSON from the device as proof of identity.

Dart
// GoogleSignInBridge and AppleSignInBridge are the reference adapters from
// examples/flutter-reference/lib/adapters/social.dart (copy them into your app).
final result = await core.auth.signInWithSocial(
  GoogleSignInBridge(serverClientId: const String.fromEnvironment('GOOGLE_SERVER_CLIENT_ID')),
);
if (result == null) {
  // user cancelled; nothing was sent
}

Apple: the adapter sends SHA-256(nonce) to Apple and returns the raw nonce as rawNonce. The server checks that the token's nonce is the hash. The backend requires a nonce for Apple.

Google: google_sign_in 6.x cannot put a nonce in the ID token, so the reference adapter returns rawNonce: null and sign-in sends no nonce. Apple name: Apple returns the user's name only on the first authorization; return it from your bridge as SocialCredential.givenName / familyName and the SDK forwards it.

Warning

Not yet tested: neither Google nor Apple sign-in has been run on a device against a real backend. The fixture server does not check nonces. Test both on devices before you ship.

Provider setup: Google sign-in, Sign in with Apple, platform setup.

Sessions and persistence

A successful sign-in returns an AuthResult (session: SessionContext, user: User). The bearer token comes from the set-auth-token response header and is stored through your SecureStore:

KeyContent
appcore.<appId>.<environmentId>.session.tokenOpaque bearer token
appcore.<appId>.<environmentId>.session.contextSessionContext JSON (scope, user id, expiry, assurance, is_guest)

What the SDK guarantees (fixture-tested):

  • Scope binding. A session whose scope.app_id or scope.environment_id differs from the manifest is rejected (SCOPE_MISMATCH) and never stored. A stored session from another app or environment is wiped by restore().
  • Rotation. If an authenticated response carries a new set-auth-token, it replaces the stored token.
  • Expiry. A 401 on any authenticated call clears the session and emits SessionEvent.expired. The SDK does not check expiresAt locally. The server decides.
  • Restart. AppCore.init restores the session from secure storage.
Dart
core.session.events.listen((e) {
  // SessionEvent.signedIn | rotated | expired | signedOut
  if (e == SessionEvent.expired) showSignIn();
});

final signedIn = core.session.isSignedIn;
final userId = core.session.userId;
final isGuest = core.session.context?.isGuest ?? false;

core.auth.me() returns the current User. Show user.visibleContacts, which leaves out internal placeholder contacts.

Guest use

There is no server-side guest account and no guest sign-in call. A signed-out user can use whatever your app shows locally, but the user-bound modules need a session. analytics.track returns false, remoteConfig.fetch() returns the empty or cached config without a request, and entitlements, inbox and purchases fail with local SESSION_REQUIRED.

On sign-in, the SDK sends this device's installation id (from core.installationId()). It goes in the x-installation-id header, and also in the body for OTP verify. The backend binds the installation to the first account that signs in on it and emits identity.guest.converted.v1 once. It never re-points the installation to another user. Locally, the SDK purges the previous owner's caches and re-registers the device.

Account linking

Linking is a two-step proof: first get a server-issued VerificationProof, then call link.

Warning

Not yet tested: account linking. startContactLink, verifyContactLink, socialLinkProof, link, unlink and linkedMethods are implemented in the SDK, but the fixture server has no routes for them, so no test sends these calls. They have not been run against a real backend either.

Dart
// Add an email address to the signed-in account.
final ch = await core.auth.startContactLink(method: 'email_otp', destination: email);
final proof = await core.auth.verifyContactLink(challengeId: ch.challengeId, code: code);
final user = await core.auth.link('email_otp', proof);

// Add Apple or Google.
final socialProof = await core.auth.socialLinkProof(AppleSignInBridge());
if (socialProof != null) await core.auth.link('apple', socialProof);
  • link and unlink(identityId) use an idempotency key derived from their inputs and are retried safely.
  • If the method already belongs to another account, the server returns a conflict. ACCOUNT_CONFLICT maps to NextAction.signInToExistingAccount. Accounts are never merged because an email address matches.
  • startContactLink and socialLinkProof do not check authMethods on the device. The server decides.

Warning

Known issue: linking Google with socialLinkProof still sends the SDK's generated nonce when the bridge returns rawNonce: null, and the server rejects a nonce the token does not carry. Linking Google fails against a real backend until this is fixed in the SDK; linking Apple is unaffected.

Signed-in sessions and linked methods: prefer the typed auth.sessionsTyped() (List<SessionSummary>, the calling session marked current) and auth.linkedMethodsTyped() (List<LinkedMethod>). The untyped sessions() and linkedMethods() are kept for compatibility. Both read the list whether the server returns it under data or items (the identity module currently uses items).

Sign out

Dart
await core.logout();                  // this device
await core.logout(allDevices: true);  // POST /v1/auth/logout-all

core.logout() flushes queued analytics for this user, detaches the device from push (DELETE /v1/messaging/devices/{installation_id}, queued and retried later if offline), revokes the server session, and then clears local session and per-user caches. The local clear happens even when the server cannot be reached.

The SDK never calls SocialSignInBridge.signOut(). Call it yourself if you want Google to show the account chooser next time.