
# The app login

`OAuth2LoginService` is the login of the app. On a phone or a desktop it is a `NativeOAuth2LoginService`: a public client with the authorization code flow and PKCE of OAuth 2.0 for Native Apps (RFC 8252), built on the registrations of the OAuth2 client (`spring.security.oauth2.client.*`). Three calls cover the life of a login: `login`, `restore` and `logout`.

## Why

Spring Security logs browsers in on a server: its `oauth2Login()` is a confidential client and keeps the tokens in its session. An app cannot keep a secret (anyone can extract it from the binary), so it logs in by itself, as a public client protected by PKCE, and keeps its tokens on the device. This service does that with every check of Spring's server-side login, so the app's code stays three lines.

## Example

```dart
@Service()
class Account {
  Account(this._login);

  final OAuth2LoginService _login;

  // At startup: the user of last time, with fresh tokens.
  Future<Authentication?> start() => _login.restore();

  // The system's login window; the user, or an exception.
  Future<Authentication?> signIn() => _login.login('keycloak');

  // Revokes and forgets the tokens; the provider's session stays.
  Future<void> signOut() => _login.logout();

  // "Switch account": also ends the provider's session.
  Future<void> switchAccount() => _login.logout(endSession: true);
}
```

```yaml
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: neon-app
            scope: openid,profile,email
            redirect-uri: dev.neon.books:/oauth2/callback
        provider:
          keycloak:
            issuer-uri: https://id.neon.books/realms/neon
```

Leave `client-secret` out: the registration is then a public client (`client-authentication-method=none`), and PKCE protects its codes.

## Per platform

| Platform | Login window | Redirect URI | Tokens |
|---|---|---|---|
| iOS, macOS | `ASWebAuthenticationSession` (a Safari sheet); Sign in with Apple's own sheet for `native-sign-in=apple` | the app's scheme (`neonbooks:/oauth2/callback`), or `https` with an associated domain (iOS 17.4, macOS 14.4) | Keychain |
| Android | a Custom Tab, the redirect caught by the package's activity | the app's scheme, or an `https` App Link | Android Keystore |
| Windows, Linux | the default browser, the redirect on a one-shot server on `127.0.0.1` (RFC 8252 §7.3) | `http://127.0.0.1/callback` (any free port) | DPAPI, the Secret Service |
| Web | none: the page goes to the server's login | the server's | none: the server keeps them (see [The web: the server logs in](web-server-mode.md)) |

On Windows and Linux the provider must accept a loopback redirect with any port (Keycloak: `http://127.0.0.1/*`; Google: a desktop client); a redirect URI with a port (`http://127.0.0.1:8400/callback`) keeps it. The setup of each platform is on [Tokens and the login window](tokens-and-login-window.md).

## login

`login('keycloak')`:

1. builds the authorization request: a random `state` (32 bytes of `Random.secure()`), a PKCE verifier (64 bytes) and its `S256` challenge, and for `openid` a random `nonce` (its SHA-256 hash is sent);
2. opens the provider's login page in the `AuthorizationWindow` and waits for the redirect back;
3. checks the redirect: back to the redirect URI, the `state` it sent (else `invalid_state_parameter`), the `iss` parameter when present or announced (RFC 9207, else `invalid_issuer`), then an `error` (`access_denied`, ...) or a `code`;
4. exchanges the code with the verifier and the redirect URI actually used;
5. for OpenID Connect checks the ID token (issuer, audience, `azp`, expiry and issue time with 60 seconds of skew, the nonce) and loads the user info, whose `sub` must be the ID token's;
6. maps the authorities (`OIDC_USER` or `OAUTH2_USER`, `SCOPE_<scope>`, then the `GrantedAuthoritiesMapper` bean), puts the `OAuth2AuthenticationToken` in the `SecurityContextHolder`, saves the tokens in the `OAuth2AuthorizedClientService` and publishes an `AuthenticationSuccessEvent`.

Any failure is an `OAuth2AuthenticationException` whose `error.errorCode` says why; a closed page is an `AuthorizationCancelledException`. Extra parameters (`prompt=login`) go in `additionalParameters`.

The ID token's signature is not checked: it comes straight from the token endpoint over TLS, which OpenID Connect Core §3.1.3.7 allows. Tokens with `alg: none` are refused all the same. Declare an `OidcIdTokenDecoder` bean to check signatures too.

## restore

`restore()` at startup brings the user back from the stored tokens, and refreshes them when they expire within a minute.

- A refresh token the provider refuses (`invalid_grant`) logs the user out; an unreachable provider does not (an app starts offline).
- The user comes back with the authorities of their login, including those an application's own `OAuth2UserService` added (kept in the login record; the user service is not called again, as a Spring session keeps the authentication of its login). The `SCOPE_` ones follow the current access token.
- A login record of a registration removed from the configuration is removed with its tokens.

## logout

`logout()` revokes the refresh and access tokens (RFC 7009, when the provider has a `revocation_endpoint`), forgets them, clears the context and publishes a `LogoutSuccessEvent`, all without a window. The user stays logged in at the provider in the system's browser, so the next login may need no password: the usual logout of a mobile app.

- `logout(endSession: true)` also ends the provider's session in the login window (OpenID Connect RP-initiated logout, with the ID token as `id_token_hint`): for "switch account". iOS and macOS announce that window with their own "... wants to use ... to Sign In" prompt.
- When the secure storage cannot delete the stored login, `logout()` still logs the user out of the running app and then throws the storage's error, so the app can tell the user the device still holds the login.

## The beans

Outside a browser, with a `spring.security.oauth2.client.registration.*` property, the package declares:

| Bean | Type | Meaning |
|---|---|---|
| `oauth2LoginService` | `NativeOAuth2LoginService` | The login |
| `authorizedClientService` | `SecretStoreOAuth2AuthorizedClientService` | Writes each authorized client as JSON to the `SecretStore` (under `oauth2.authorized-client.<registration>.<principal>`; the login keeps what `restore` needs under `oauth2.login`). It replaces the OAuth2 client's in-memory one |
| `appleIdSignIn` | `AppleIdSignIn` | On iOS and macOS, Sign in with Apple's sheet (see [Providers](providers.md)) |
| `platformDPoPKey` | `PlatformDPoPKey` | The app's DPoP key (see [DPoP](dpop.md)) |

Every bean of the package backs off when the application declares one of its type: `SecretStore`, `SecretTemplate`, `AuthorizationWindow`, `AppleIdSignIn`, `OAuth2AuthorizedClientService`, `OAuth2LoginService`, `PrincipalNotifier`, `DPoPKey`, and on the web `BrowserPage` and `HttpTransport`. Nothing in the package logs a token, a code, a verifier or a secret.

## Calling APIs with the token

The OAuth2 client's Feign interceptor sends the access token of the registration named like the Feign client (or `spring.feign.oauth2.client-registration-id`), refreshing it when needed, with DPoP proofs when the tokens are bound. List `spring_boot_starter_feign` for Feign clients.

## In Spring (Java)

Spring has no counterpart: its `oauth2Login()` logs browsers in on a server. The checks are those of its `OAuth2LoginAuthenticationFilter`, `OidcAuthorizationCodeAuthenticationProvider` and `OidcUserService`.

## See also

- [Tokens and the login window](tokens-and-login-window.md)
- [The web: the server logs in](web-server-mode.md)
- [All properties](properties.md)
