
# Authorized clients

An `OAuth2AuthorizedClient` holds the tokens of one principal for one registration: the access token, maybe a refresh token and an ID token. The `OAuth2AuthorizedClientManager` hands out authorized clients whose access token is valid: it gets a client credentials token, or refreshes an expiring one, and stores the result in the `OAuth2AuthorizedClientService`.

## Why

A token expires; ten calls that notice at the same time must not refresh it ten times (a rotating refresh token sent twice is refused, and the user is logged out). A refresh the provider refuses must remove the stored client, but an unreachable provider must not. The manager does this once, for every caller.

## Example

```dart
@Service()
class PartnerApi {
  PartnerApi(this.manager, this.transport);

  final OAuth2AuthorizedClientManager manager;
  final HttpTransport transport;

  Future<HttpResponse> orders() async {
    final client = await manager.authorize(
      OAuth2AuthorizeRequest.withClientRegistrationId('partner')
          .principal(anonymousAuthentication)   // client credentials: no user
          .build(),
    );
    final request = HttpRequest(
      method: HttpMethod.get,
      url: Uri.parse('https://api.partner.example/orders'),
    )..headers.set('Authorization', 'Bearer ${client!.accessToken.tokenValue}');
    return transport.send(request);
  }
}
```

For Feign clients, the interceptor does this for you (see [Tokens on Feign calls](feign.md)).

## The manager

| Type | Role |
|---|---|
| `OAuth2AuthorizedClientManager` | `authorize(request)`: a valid authorized client, or `null` when it cannot (for example no login yet for an `authorization_code` registration). |
| `OAuth2AuthorizeRequest.withClientRegistrationId(id)`, `.withAuthorizedClient(client)` | The request (a new one, or a re-authorization): `.principal(authentication)` or `.principalName('name')`, then `.build()`. |
| `AuthorizedClientServiceOAuth2AuthorizedClientManager` | The default manager, over the registration repository and the authorized client service. |
| `OAuth2AuthorizedClientProvider` | One way to authorize: `AuthorizationCodeOAuth2AuthorizedClientProvider`, `RefreshTokenOAuth2AuthorizedClientProvider`, `ClientCredentialsOAuth2AuthorizedClientProvider`, combined by `DelegatingOAuth2AuthorizedClientProvider` or `OAuth2AuthorizedClientProviderBuilder`. |

What the default manager does:

- an `authorization_code` client is refreshed with its refresh token when the access token expires within a minute;
- a `client_credentials` client gets a new token the same way;
- concurrent callers for one registration and principal share one authorization, so a rotating refresh token is never sent twice;
- a refresh the provider refuses (`invalid_grant`, `invalid_token`) removes the stored client; an unreachable provider does not;
- a refreshed ID token is checked against the old one (same issuer and subject), as OpenID Connect Core §12.2 says.

## OAuth2AuthorizedClient

| Member | Meaning |
|---|---|
| `clientRegistration` | The registration. |
| `principalName` | Whose tokens these are. |
| `accessToken` | The `OAuth2AccessToken`: `tokenValue`, `tokenType` (`bearer` or `dpop`), `issuedAt`, `expiresAt`, `scopes`. |
| `refreshToken` | The refresh token, if any. |
| `idToken` | The ID token, kept so the refresh can check a new one and a logout without a session (an app after a restart) can send it as `id_token_hint`. |

## Storage

The `OAuth2AuthorizedClientService` keeps authorized clients by registration and principal: `loadAuthorizedClient`, `saveAuthorizedClient`, `removeAuthorizedClient`.

- The starter's, as Spring Boot's, is an `InMemoryOAuth2AuthorizedClientService`: right for client credentials tokens, forgotten when the program stops.
- Declare an `OAuth2AuthorizedClientService` bean to keep them elsewhere (a database).
- `spring_boot_starter_flutter_security` declares one on the platform's secure storage, so an app's login survives a restart.
- On a server, `oauth2Login()` keeps the user's tokens in the session through the security starter's `OAuth2AuthorizedClientRepository`.

## The token clients

The manager calls the token endpoint through three `OAuth2AccessTokenResponseClient` beans, each on the `HttpTransport` of `spring_web_dart`:

| Bean | Grant |
|---|---|
| `DefaultAuthorizationCodeTokenResponseClient` | `authorization_code`, with the PKCE verifier (PKCE is on for every `authorization_code` registration). |
| `DefaultRefreshTokenTokenResponseClient` | `refresh_token`. |
| `DefaultClientCredentialsTokenResponseClient` | `client_credentials`. |

They authenticate the client as the registration says (`client_secret_basic`, `client_secret_post`, `none`, or a JWT secret), and send DPoP proofs for a DPoP registration. The code token request leaves `redirect_uri` out when the authorization request had none (RFC 6749 §4.1.3).

## Tokens on other requests

For a request the starter does not make (an `HttpTransport` call of your own, a WebSocket handshake), `OAuth2AccessTokenHeaders` writes the headers by the token's type: `Bearer <token>`, or `DPoP <token>` and a fresh proof.

```dart
// The token of the logged-in user on a WebSocket handshake.
final client = await manager.authorize(request);
final headers = await OAuth2AccessTokenHeaders(dPoPKey: key).of(
  client!.accessToken,
  method: 'GET',
  url: handshake.url, // wss://api.example.com/ws/chat
);
headers.forEach(handshake.headers.set);
```

A `ws` / `wss` URL goes into the proof's `htu` as `http` / `https`, since a handshake is an HTTP `GET`. Browsers cannot set headers on a handshake; a page sends its session cookie instead.

## In Spring (Java)

```java
OAuth2AuthorizedClient client = manager.authorize(
    OAuth2AuthorizeRequest.withClientRegistrationId("partner").principal("shop").build());
```

The types are Spring Security's; every call returns a `Future`. The default manager needs its provider (Spring defaults to client credentials alone), runs one authorization at a time per registration and principal, and removes the stored client after `invalid_grant` or `invalid_token`. The token clients are Spring 7's `RestClient*TokenResponseClient` on the `HttpTransport`. Not here yet: a database-backed service, `@ClientRegistrationId` on HTTP clients.

## See also

- [Tokens on Feign calls](feign.md)
- [Registrations](registrations.md)
- [DPoP](dpop.md)
