
# 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`](../spring-security-core/login-session.md).

## 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

```dart
@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.

```dart
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. |

- **One login.** The user is Spring Security's: the `Authentication` is in the `SecurityContextHolder`, an `AuthenticationSuccessEvent` is published at each login and restore, a `LogoutSuccessEvent` at `logout`.
- **Roles** are `ROLE_<role>` for each string in `app_metadata.roles`, as [on a server](security.md). `user_metadata` grants nothing: a user can write it.

```dart
@PreAuthorize("hasRole('editor')")
Future<void> publish(Post post) async { ... }
```

## The session

- **Kept across restarts.** The session (the two tokens and the user) is kept in the application's `SecretStore` when `spring.supabase.auth.persist-session` is `true` (the default). Without a `SecretStore` bean it is kept in memory. [spring_boot_starter_flutter_security](../spring-boot-starter-flutter-security/tokens-and-login-window.md) declares a store over the platform's secure storage (the Keychain, the Keystore).
- **Restored at startup.** `restore()` runs by itself when the application starts, and never fails the start. A session whose access token has expired is refreshed first. Without a network the user is restored all the same, and the tokens are refreshed at their next use. A stored value that cannot be read is removed.
- **Refresh.** `accessToken()` gives a token that is not about to expire: one that expires within `refresh-margin` (30 s) is refreshed first, and however many callers wait, one request is made. With `auto-refresh` (the default) a timer does it before the expiry. `refreshSession()` does it now.
- **A refresh token is used once.** The new one replaces it at once.
- **When Auth refuses the refresh token** (`refresh_token_not_found`, `refresh_token_already_used`, `session_not_found`, `session_expired`, `user_not_found`, `user_banned`, `invalid_grant`: `SupabaseAuth.sessionEndingCodes`), the user is signed out here. `refreshSession()` then throws a `SupabaseSessionExpiredException`; `accessToken()` gives `null`.
- **When Auth cannot be reached**, or answers with a rate limit or a failure of its own, the session stays and the call fails.

## Signing out

```dart
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:

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

- **Before the request:** `redirectTo` must be one of the list, exactly as it is written there; the first is used when none is given. Any other is an `ArgumentError`, and no request is made. The same addresses must be in the project's own list of redirect URLs.
- **When it comes back:** the redirect must be the address the login asked for (the same scheme, host, port and path) and carry a `code`. Another address, or one that carries an `error`, is an `AuthenticationException`.
- **PKCE (S256).** Auth gets only the SHA-256 of a verifier made when the login starts. The code that comes back is worth nothing without the verifier, which never leaves the application except, once, to Auth itself.

With a login window:

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

It needs an `AuthorizationWindow` bean ([spring_boot_starter_flutter_security](../spring-boot-starter-flutter-security/tokens-and-login-window.md) 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:

```dart
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 `AuthenticationException`s, 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` |

- No answer at all is a `SupabaseUnavailableException` (`isTimeout` for a timeout).
- A method that needs a user, called when nobody is signed in, throws an `AuthenticationCredentialsNotFoundException`.
- No token, password or code is ever in a message or a log: should an answer repeat one, it is replaced by `[PROTECTED]`.

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:

```dart
@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.

```dart
final user = await admin.createUser(
  email: 'ada@example.com',
  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

- [LoginSession and the shared interfaces](../spring-security-core/login-session.md)
- [Security on a server](security.md)
- [Who a call is made as](credentials.md)
- [Method security](../spring-security-core/method-security.md)
- [spring_boot_starter_flutter_security](../spring-boot-starter-flutter-security/index.md)
