Client credentials

This documentation was generated with the assistance of AI. Please report any inaccuracies.

A service calls an API as itself, with no user involved. service-client started with the client-credentials profile authenticates to the authorization server with the client_credentials grant, receives an access token whose subject is its own client id, and calls GET /api/documents on the resource server with it. The token is cached and renewed shortly before it expires, so a service making many calls asks for a new token only when needed.

At a glance
  • Actors: service-client (the client application), auth-server (port 9000), resource-server (port 8081).

  • Clients involved: a confidential client registered for service-client (default id service-client, env SERVICE_CLIENT_ID). It is not seeded: register it through POST /api/admin/clients with grant type client_credentials, the scope documents.read and the audience resource-server.

  • Preconditions: Spring profile client-credentials on service-client; a client authentication method the client is registered for (see Client authentication); for client_secret_basic, the generated secret in SERVICE_CLIENT_SECRET.

  • Endpoints: POST /oauth2/token (authorization server), GET /api/documents (resource server).

Steps

  1. ServiceClientApplication starts with the client-credentials profile, which activates ClientCredentialsCli (a CommandLineRunner) and binds application-client-credentials.yml: service-client.auth.method (SERVICE_CLIENT_AUTH_METHOD, default client_secret_basic), client-id, client-secret, token-uri (SERVICE_CLIENT_TOKEN_URI, default http://localhost:9000/oauth2/token), scopes (SERVICE_CLIENT_SCOPES, default documents.read), refresh-before (SERVICE_CLIENT_REFRESH_BEFORE, default PT60S) and service-client.resource-server.base-uri (SERVICE_CLIENT_RESOURCE_SERVER_URI, default http://localhost:8081).

  2. ServiceClientRegistrationMapper builds a Spring Security ClientRegistration with the id service-client, grant type client_credentials and the configured authentication method; OAuth2ClientConfiguration keeps it in an InMemoryClientRegistrationRepository.

  3. ClientCredentialsCli runs ListDocumentsUseCase, which calls the domain port DocumentGateway, implemented by RestDocumentGateway over the client generated from the resource server’s contract.

  4. Before the call, the interceptor built by ResourceServerInterceptors asks the AuthorizedClientServiceOAuth2AuthorizedClientManager for an authorized client. With no cached token, the client-credentials provider posts grant_type=client_credentials and scope to /oauth2/token through the RestClientClientCredentialsTokenResponseClient that TokenEndpointClients configures (assertion, mutual TLS or DPoP headers are added there when enabled).

  5. The authorization server authenticates the client, checks the grant type and the scopes and issues a signed JWT (IssuedTokenClaims sets aud to the client’s configured audiences). No refresh token is issued for this grant.

  6. The token is stored in the InMemoryOAuth2AuthorizedClientService and sent as Authorization: Bearer (or DPoP, see Sender-constrained tokens) to GET /api/documents.

  7. The resource server validates the token (see Resource server token validation) and requires SCOPE_documents.read. The documents are printed as JSON lines.

  8. On a later call the manager reuses the cached token while more than refresh-before of its lifetime is left; the value is passed to the provider as its clock skew, so a token that expires within that margin is replaced by a new client_credentials request before it is used.

  9. With SERVICE_CLIENT_PRINT_ACCESS_TOKEN=true (service-client.cli.print-access-token) ClientCredentialsCli also prints the token, obtained through ServiceTokens.

        final var clientCredentials = OAuth2AuthorizedClientProviderBuilder.builder()
                .clientCredentials(grant -> grant
                        .accessTokenResponseClient(tokenClients.clientCredentials())
                        .clockSkew(properties.refreshBefore()))
                .build();
        final var clientCredentialsManager =
                new AuthorizedClientServiceOAuth2AuthorizedClientManager(registrations, clients);
        clientCredentialsManager.setAuthorizedClientProvider(clientCredentials);
sequenceDiagram autonumber participant S as service-client participant M as Authorized client manager participant A as auth-server participant R as resource-server S->>M: authorize registration service-client alt no cached token or it expires within refresh-before M->>A: POST /oauth2/token grant_type=client_credentials scope=documents.read A->>A: authenticate client, check grant and scopes A-->>M: 200 access_token, token_type, expires_in, scope M->>M: store token in memory else cached token still valid M->>M: reuse cached token end M-->>S: access token S->>R: GET /api/documents with Authorization Bearer token R->>R: validate signature, iss, exp, aud and SCOPE_documents.read R-->>S: 200 documents
flowchart TD A[Call needs a token] --> B{"Token cached?"} B -- No --> D["POST /oauth2/token (client_credentials)"] B -- Yes --> C{"Expires within refresh-before?"} C -- Yes --> D C -- No --> E[Reuse cached token] D --> F{"Client authenticated and grant allowed?"} F -- No --> G["401 invalid_client or 400 unauthorized_client"] F -- Yes --> H[Store new token] H --> I[Call resource server] E --> I

Tokens and claims

  • Access token: a JWT signed with the server’s active key (or a reference token if the client is registered with "accessTokenFormat": "reference"). No refresh token and no ID token.

  • sub is the client id; aud is the list of the client’s configured audiences (default the client id, so register resource-server); scope holds the granted scopes.

  • No roles and no tenant: IssuedTokenClaims adds them only to tokens that have a user.

  • With tls_client_auth and certificateBoundAccessTokens, the token carries cnf.x5t#S256; with DPoP, cnf.jkt and token_type=DPoP.

How it is tested

  • e2e-tests: ClientCredentialsEndToEndIT runs the packaged service-client jar against the packaged authorization and resource servers, once per authentication method and once with DPoP, and checks sub and cnf.

  • service-client/infrastructure/resourceserver: ResourceServerAdapterIT (WireMock) checks that a valid token is reused across calls (listDocuments_whenTokenIsValid_reusesItAcrossCalls) and that a token expiring within the margin is replaced on every call (listDocuments_whenTokenExpiresWithinTheMargin_requestsANewTokenEachCall).

  • auth-server/boot: TokenFlowIT (accessToken_whenIssuedToAClient_hasAudienceButNoUserClaims) and ClientAuthenticationIT.