Guides

Access policy

Refuse a sign-in or an account switch before it happens.

An AuthPolicy can reject an operation. A rejection throws AuthDeniedException to the caller and changes nothing. Override only the checks you need; the others allow.

final class CompanyOnly extends AuthPolicy {
  const CompanyOnly();

  @override
  AuthDecision beforeSessionStart(String providerId, AuthSignInResult result) {
    final email = result.user.email ?? '';
    return email.endsWith('@acme.com')
        ? const AuthDecision.allow()
        : const AuthDecision.deny('Sign in with your Acme account.');
  }
}

final authyra = await Authyra.initialize(
  storage: SecureAuthStorage(),
  providers: [apiProvider, googleProvider],
  policy: const CompanyOnly(),
);

The checks

MethodCalledTypical use
beforeSignIn(providerId, params)Before the provider runs.Rate limiting, disabling a provider remotely.
beforeSessionStart(providerId, result)After authentication, before the session is stored.Allowed domains, a single account per device, required claims.
beforeSwitch(from, to)When switchTo changes the active session. Not called by a sign-in that activates its session, nor by the fallback after a sign-out.Locking an account switch behind a check.

Each can be asynchronous (FutureOr<AuthDecision>).

try {
  await authyra.signIn('google');
} on AuthDeniedException catch (error) {
  showError(error.reason);
}

One account per device

final class SingleAccount extends AuthPolicy {
  const SingleAccount(this.sessions);

  final List<AuthSession> Function() sessions;

  @override
  AuthDecision beforeSessionStart(String providerId, AuthSignInResult result) {
    final others = sessions().where((s) => s.user.id != result.user.id);
    return others.isEmpty
        ? const AuthDecision.allow()
        : const AuthDecision.deny('Sign out first to use another account.');
  }
}

Sign-out is never gated: a user must always be able to end a session.

Copyright © 2026