
# DPoP

A `Bearer` token works for whoever holds it. With DPoP (RFC 9449) the provider binds the tokens to a key pair of the app: every token request and every API call carries a short proof signed by the key, so a token copied out of the app (a log, a backup, a proxy) is useless without the device. The OAuth2 client does it when the registration's `dpop` says so; this package gives it the key, in the safest place each platform has.

## Why

The key must live as long as the tokens, or a restart would mean a new login, and it should never be readable by the app's own code. On phones that means hardware: the Secure Enclave or the Android Keystore sign without ever showing the key.

## Example

```yaml
spring:
  security:
    oauth2:
      client:
        registration:
          keycloak:
            client-id: neon-app
            redirect-uri: dev.neon.books:/oauth2/callback
            dpop: auto      # auto (default): when the provider announces it; true: always; false: never
```

Nothing else: the token clients, the user services and the Feign interceptor use the `DPoPKey` bean by themselves.

## Where the key lives

The package declares the app's `DPoPKey` bean (`platformDPoPKey`, a `PlatformDPoPKey`). It is made at the first proof, not at startup.

| Platform | Where the key lives | Who signs |
|---|---|---|
| iOS, macOS | the Secure Enclave (EC P-256, permanent, tagged `<bundle id>.spring_dpop_key`, after the first unlock, this device only) | the Secure Enclave |
| iOS, macOS without a usable Secure Enclave | a software key of the Keychain with the same tag and protection | the system's Security framework |
| Android | the Android Keystore (EC P-256), in StrongBox when the phone has it, else the trusted execution environment | the Keystore |
| Windows, Linux | a key made in Dart, kept as a private JWK in the `SecretStore` (`oauth2.dpop-key`) | the app (`SecretStoreDPoPKey`) |
| Web, spa mode | a non-extractable WebCrypto key in IndexedDB (see [Spa mode](web-spa-mode.md)) | the browser |
| Web, server mode | none: the page holds no tokens | |

`PlatformDPoPKey.storage` says where the key ended up (`secureEnclave`, `keychain`, `strongBox`, `trustedEnvironment`, `software`, `secretStore`). No key material, proof or token is ever logged.

## When the key is lost

The key never leaves the device: an app restored on another phone, an Android app reinstalled, or a wiped Keystore has none. The stored tokens carry the thumbprint of their key, so they are dropped when loaded, `restore()` finds no login, and the user logs in again. On iOS, where Keychain items outlive the app, each installation gets an id: the first start after a reinstall removes the stored values and the key, so a reinstalled app does not log the last user in again. An update never loses them.

## Logout

`logout()` deletes the key after revoking and forgetting the tokens; the next login makes a new one, so two logins on the device cannot be linked by their key. `SecretStore.deleteAll()` removes the desktop key (a value of the store), not the Secure Enclave's or the Keystore's; call `PlatformDPoPKey.delete()` for those.

## Calls of your own and WebSocket handshakes

The Feign interceptor sends `Authorization: DPoP <token>` and a proof by itself. For a request the framework does not make, `OAuth2AccessTokenHeaders` of the OAuth2 client writes the headers by the token's type. For a WebSocket handshake the proof's `htu` is the `http(s)` form of the `ws(s)` URL:

```dart
// A handshake interceptor of the app (spring_boot_starter_websocket).
@Component()
class ChatHandshake implements WebSocketHandshakeInterceptor {
  ChatHandshake(this._tokens, this._dPoPKey);

  final OAuth2AuthorizedClientManager _tokens;
  final DPoPKey? _dPoPKey;

  @override
  Future<void> apply(WebSocketHandshake handshake) async {
    final user = SecurityContextHolder.getContext().authentication;
    if (user == null) return;
    final client = await _tokens.authorize(
      OAuth2AuthorizeRequest.withClientRegistrationId('keycloak')
          .principal(user)
          .build(),
    );
    final headers = await OAuth2AccessTokenHeaders(dPoPKey: _dPoPKey).of(
      client!.accessToken,
      method: 'GET',
      url: handshake.url,
    );
    headers.forEach(handshake.headers.set);
  }
}
```

Browsers cannot set headers on a WebSocket handshake: a page in server mode sends its session cookie with it.

An app declares its own `DPoPKey` bean to keep the key elsewhere; the package's then backs off (and `logout()` leaves the app's key alone).

## The property

| Key | Type | Default | Meaning |
|---|---|---|---|
| `spring.security.oauth2.client.registration.<id>.dpop` | `auto`, `true`, `false` | `auto` | `auto` binds the tokens when the provider's metadata announces DPoP (Keycloak, Okta, Auth0, ...); `true` always; `false` never |

## In Spring (Java)

Spring Security 7 accepts DPoP tokens on resource servers only; it has no DPoP on the client's side, and Java has no apps.

## See also

- [The app login](app-login.md)
- [Spa mode](web-spa-mode.md)
- [Tokens and the login window](tokens-and-login-window.md)
