Sign-in in a client application

SupabaseAuth (the bean supabaseAuth) is the login of a client application through Supabase Auth. It signs users up and in, keeps their session fresh and across restarts, and signs them out. It is also the application's LoginSession.

Why

A login is more than one request. The tokens must be kept safely between runs, refreshed before they expire by one request however many callers wait, and dropped when the server ends the session. A redirect that comes back must be the one that was asked for. And the rest of the application should see the user where it already looks: the security context. SupabaseAuth does these once, so every call to Supabase and every @PreAuthorize see the same user.

Example

@Service()
class Account {
  Account(this.auth);

  final SupabaseAuth auth;

  Future<void> signIn(String email, String password) async {
    try {
      await auth.signInWithPassword(email: email, password: password);
    } on BadCredentialsException {
      showError('Wrong email or password');
    } on AuthenticationException catch (e) {
      if (e case SupabaseAuthFailure(errorCode: 'email_not_confirmed')) {
        showError('Confirm your email address first');
      }
    }
  }

  String? get email => auth.user?.email;

  Future<void> signOut() => auth.logout();
}

After signInWithPassword every call to Supabase is made as the user, and @PreAuthorize and the security context see them too.

Signing up and in

Method What it does
signUp(password:, email:, phone:, data:, redirectTo:) Creates a user with an email or a phone and a password; data is their user_metadata. Completes with the signed-in user when the project confirms new users by itself, else with null: nobody is signed in until the address is confirmed.
signInWithPassword(password:, email:, phone:) Signs in with an email or a phone and a password. Wrong credentials are a BadCredentialsException; Auth does not say which part was wrong.
signInWithOtp(email:, phone:, createUser:, redirectTo:) Sends a one-time code or a magic link to an email, or a code to a phone. Nobody is signed in yet. With createUser (the default) an unknown address becomes a new user.
verifyOtp(token:, type:, email:, phone:) Signs in with the code; type (SupabaseOtpType) says what the code was sent for: email, sms, signup, invite, magiclink, recovery, emailChange, phoneChange.
signInWithIdToken(provider:, idToken:, accessToken:, nonce:) Signs in with the ID token a provider's own SDK gave (the native Google or Apple sign-in).
signInWithProvider(provider, scopes:, redirectTo:, queryParameters:) Opens the provider's page (google, github, apple, …) in the application's AuthorizationWindow and exchanges the code that comes back.
authorizationUrl(provider, scopes:, redirectTo:, queryParameters:) The address of the provider's page, for an application that opens the browser itself.
completeSignIn(redirect) Finishes the login that waits for its redirect: a provider's answer, a magic link, the confirmation of a sign-up, a password reset.
exchangeCode(code) Exchanges the authorization code of the login that waits; completeSignIn also checks where the code came from.
resetPassword(email, redirectTo:) Sends the email that lets the user set a new password.

Give an email or a phone, one of the two; anything else is an ArgumentError before a request is made. Auth answers the same for an address that is taken (sign-up) or unknown (password reset), so nobody learns who has an account.

await auth.signInWithOtp(email: email);
// The user types the code of the email:
await auth.verifyOtp(email: email, token: code, type: SupabaseOtpType.email);

The signed-in user

Member Meaning
user The SupabaseUser, or null: id, email, phone, role, appMetadata, userMetadata, roles, createdAt, emailConfirmedAt, lastSignInAt, isAnonymous…
authentication The SupabaseAuthenticationToken in the security context: its name is the user's id, its principal the SupabaseUser, its credentials the access token.
isLoggedIn Whether a user is signed in.
authenticationChanges A stream of the user after each change; null after a logout.
updateUser(email:, password:, data:) Changes the user: their email (Auth confirms the new address first), their password, or data, merged into user_metadata.
reloadUser() Reads the user from Auth again, after their address was confirmed or the project changed their roles.
@PreAuthorize("hasRole('editor')")
Future<void> publish(Post post) async { ... }

The session

Signing out

await auth.logout();                                   // this session
await auth.logout(scope: SupabaseLogoutScope.global);  // every device
await auth.logout(scope: SupabaseLogoutScope.others);  // every session but this one

The session is forgotten here first (memory, the SecretStore, the security context, the refresh timer), then revoked at Auth. The user is signed out here even when Auth cannot be reached: a logout never depends on the network. With others the user stays signed in here, and a failure is thrown.

Redirects and PKCE

A login through a provider, a magic link, a sign-up confirmation and a password reset come back to the application at an address. The addresses are listed, and nothing else is accepted:

spring:
  supabase:
    auth:
      redirect-urls:
        - com.example.app://login
        - https://app.example.com/login

With a login window:

await auth.signInWithProvider('github', scopes: ['read:user']);

It needs an AuthorizationWindow bean (spring_boot_starter_flutter_security declares one). Without it, it throws a StateError. A window the user closed is an AuthorizationCancelledException. A desktop window may take a free port of the loopback address; nothing else of the address may change.

Without one, the application opens the browser itself:

final url = await auth.authorizationUrl('google');
await launchUrl(url);
// Later, from the application's deep link:
await auth.completeSignIn(link);

The verifier of such a login, and of an email link, waits in the SecretStore, so the application may be restarted in between. Starting another login replaces it: one login waits at a time. The verifier is used once.

A password reset is the same flow: resetPassword(email), then completeSignIn(link) signs the user in, and updateUser(password: …) sets the password.

Errors

A failed login is one of Spring Security's AuthenticationExceptions, so code written against Spring's types does not change. Each also carries Auth's error code and the HTTP status (SupabaseAuthFailure.errorCode, statusCode).

Auth's code Exception Spring's type
invalid_credentials, invalid_grant, otp_expired, bad_code_verifier, flow_state_* SupabaseBadCredentialsException BadCredentialsException
email_not_confirmed, phone_not_confirmed, provider_email_needs_verification SupabaseAccountDisabledException DisabledException
user_banned SupabaseAccountLockedException LockedException
refresh_token_not_found, refresh_token_already_used, session_not_found, session_expired SupabaseSessionExpiredException CredentialsExpiredException
user_not_found SupabaseUserNotFoundException UsernameNotFoundException
weak_password SupabaseWeakPasswordException (reasons: length, characters, pwned) AuthenticationException
a status of 500 and above SupabaseAuthServiceException AuthenticationServiceException
anything else (a rate limit, a request Auth could not accept) SupabaseAuthenticationException AuthenticationException

An error code of your own project (a hook that refuses a login) gets an exception of its own from a SupabaseAuthErrorTranslator bean, asked before the starter's own:

@Component()
class TrialEnded implements SupabaseAuthErrorTranslator {
  @override
  AuthenticationException? translate(SupabaseAuthError error) =>
      error.code == 'trial_ended'
          ? AccountExpiredException(error.message)
          : null;
}

The admin API

SupabaseAuthAdmin (the bean supabaseAuthAdmin) creates, reads, changes and deletes the project's users, as the service role. It is only on a server: its module is ModulePlatform.server (the Dart VM or an AOT executable), so a Flutter app (on a phone, a desktop or the web) and a browser build have none of its code, and an app cannot be made to call it. An edge function, compiled with -DSPRING_ALL_PLATFORMS=true, has it. Without spring.supabase.service-role-key a call fails with a StateError before any request.

final user = await admin.createUser(
  email: '[email protected]',
  password: password,
  emailConfirm: true,
  appMetadata: {'roles': ['editor']},
);
await admin.updateUser(user.id, appMetadata: {'roles': ['admin']});
await admin.deleteUser(user.id);
Method What it does
createUser(email:, phone:, password:, emailConfirm:, phoneConfirm:, appMetadata:, userMetadata:) Creates a user. With emailConfirm the address counts as confirmed and the user can sign in at once.
user(id) The user, or null.
users(page:, perPage:) One page of the users; page starts at 1, perPage is 50 by default.
updateUser(id, …, banDuration:) Changes only what is given. appMetadata and userMetadata are merged (a key with the value null is removed); banDuration: '24h' bans, 'none' lifts a ban.
deleteUser(id, softDelete:) Deletes the user with their sessions.

Roles belong in appMetadata (roles): only this API writes it. An id that is not a UUID is an ArgumentError.

Not supported

Anonymous sign-in, multi-factor authentication, linking identities, SSO (SAML), sending a confirmation again; in the admin API, invitations and generated links.

The properties

Key Type Default Meaning
spring.supabase.auth.enabled bool true false declares neither supabaseAuth nor supabaseAuthAdmin (which is on a server only).
spring.supabase.auth.redirect-urls List<String> empty The addresses a login may come back to; the first is the default.
spring.supabase.auth.persist-session bool true Whether the session is kept in the SecretStore.
spring.supabase.auth.auto-refresh bool true Whether a timer refreshes the access token before it expires.
spring.supabase.auth.refresh-margin Duration 30s How long before its expiry an access token counts as expired.

In Spring (Java)

No counterpart: Spring Security logs in the users of a server. The nearest are oauth2Login() and OAuth2AuthorizedClientManager. The exceptions and the events are Spring Security's.

See also