
# LoginSession and the shared interfaces

A client application (a Flutter app, a command-line tool) has one user at a time, logged in by some provider: an OAuth 2.0 / OpenID Connect provider, a backend-as-a-service such as Supabase, a login of your own. How the user logs in differs; what the rest of the application needs does not. `spring_security_core` has that common part as interfaces only, without any provider or platform code, so they work anywhere Dart runs.

## Why

An HTTP client that adds the user's token, a widget that shows the user's name and a route guard should not know which provider logged the user in. Written against `LoginSession`, they are written once. And a provider's login can keep its tokens (`SecretStore`) and open a login page (`AuthorizationWindow`) without depending on Flutter: the platform implementations are in another package.

## Example

```dart
// Adds the user's token to a request, whatever logged the user in.
final class UserTokenHeaders {
  UserTokenHeaders(this.session);

  final LoginSession session;

  Future<Map<String, String>> headers() async {
    final token = await session.accessToken();
    return {if (token != null) 'authorization': 'Bearer $token'};
  }
}
```

## The interfaces

| Type | What it is |
|---|---|
| `LoginSession` | The current login: who is logged in, a token for a request, the login of the last run, the logout. |
| `SecretStore` | Where a login's tokens are kept between runs: strings by key. `InMemorySecretStore` is the one for tests and for platforms without secure storage. |
| `AuthorizationWindow` | A provider's login page in the system's login window, and the redirect back. Throws `AuthorizationCancelledException` when the user closes it. |
| `OAuth2Token` | What every OAuth 2.0 token has: `tokenValue`, `issuedAt`, `expiresAt`. |
| `sha256Digest(bytes)`, `pkceS256Challenge(verifier)` | SHA-256, and the `S256` code challenge of PKCE (RFC 7636), for a login that is not built on the OAuth2 client. |

They are interfaces and functions only: the package declares no bean of them.

## LoginSession

| Member | Meaning |
|---|---|
| `Authentication? get authentication` | Who is logged in now, or `null`. Reading it starts no request. |
| `bool get isLoggedIn` | Whether `authentication` is not `null` and is authenticated. |
| `Stream<Authentication?> get authenticationChanges` | The user after each change: a login, a refresh that changed the user's data, and `null` after a logout or a refresh the provider refused. A broadcast stream; it does not repeat the current value to a new listener, so read `authentication` first. |
| `Future<String?> accessToken()` | An access token that is not about to expire, or `null` when nobody is logged in. A token close to its expiry is refreshed first; concurrent calls share one refresh. |
| `Future<Authentication?> restore()` | Brings back the login of the last run from where the implementation keeps it, refreshing its tokens when needed. `null` when there was none or it can no longer be used. |
| `Future<void> logout()` | Ends the login: the tokens are forgotten (and revoked at the provider when it can do that), the security context is cleared, and `authenticationChanges` reports `null`. |

What an implementation promises:

- **The security context is kept in step.** The `authentication` it reports is the one of the current [security context](security-context.md), so `@PreAuthorize` and the code that reads the context see the same user.
- **A refused refresh logs the user out:** `accessToken()` completes with `null` and `authenticationChanges` reports `null`. A refresh that could not be made (no network) completes with an error and logs nobody out.
- **A logout does not depend on the provider:** the user is logged out here even when the provider could not be told.
- **Tokens are credentials:** never logged, and kept between runs only in a `SecretStore`.

How the user logs in (a password, a one-time code, the provider's page) is not in the interface: each provider's own type has it.

Implementations: [`SupabaseAuth`](../spring-boot-starter-supabase/auth.md) of the Supabase starter. The OAuth 2 login of the Flutter security starter (`OAuth2LoginService`) is a type of its own and does not implement the interface.

## SecretStore

```dart
abstract interface class SecretStore {
  Future<String?> read(String key);
  Future<void> write(String key, String value);
  Future<void> delete(String key);
  Future<Set<String>> keys();
  Future<void> deleteAll();
}
```

`InMemorySecretStore` keeps the values in a map: they are gone when the application stops. [spring_boot_starter_flutter_security](../spring-boot-starter-flutter-security/tokens-and-login-window.md) has `PlatformSecretStore` over the platform's secure storage (the Keychain, the Keystore) and declares it as the application's `SecretStore` bean.

## AuthorizationWindow

```dart
abstract interface class AuthorizationWindow {
  Future<Uri> authorize({
    required Uri redirectUri,
    required Uri Function(Uri redirectUri) authorizationUri,
  });
}
```

`authorize` opens the address that `authorizationUri` makes for the redirect address the window really uses (a desktop window may take a free port of the loopback address), and completes with the redirect that came back. A window the user closed throws an `AuthorizationCancelledException`. The platform windows are in `spring_boot_starter_flutter_security`.

## OAuth2Token

`OAuth2Token` is Spring's interface of the same name. The OAuth2 client's access, refresh and ID tokens (`AbstractOAuth2Token`) and the security starter's `Jwt` implement it, so code can ask any of them for `tokenValue` and `expiresAt`. A bearer token of a server's request is found this way:

```dart
final credentials = SecurityContextHolder.getContext().authentication?.credentials;
if (credentials is OAuth2Token) {
  forward(credentials.tokenValue);
}
```

## Where they were before

`SecretStore`, `InMemorySecretStore`, `AuthorizationWindow` and `AuthorizationCancelledException` moved here from `spring_boot_starter_flutter_security`, which still exports them: an application that imports that package changes nothing.

## In Spring (Java)

Spring has no `LoginSession`, `SecretStore` or `AuthorizationWindow`: Spring Security logs in the users of a server, one per request, and its OAuth 2.0 client keeps tokens per user and registration (`OAuth2AuthorizedClientManager`). `OAuth2Token` is `org.springframework.security.oauth2.core.OAuth2Token`.

## See also

- [The security context](security-context.md)
- [Authentication](authentication.md)
- [Supabase: sign-in in a client application](../spring-boot-starter-supabase/auth.md)
- [spring_boot_starter_flutter_security](../spring-boot-starter-flutter-security/index.md)
