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.
-
Actors:
service-client(the client application),auth-server(port 9000),resource-server(port 8081). -
Clients involved: a confidential client registered for
service-client(default idservice-client, envSERVICE_CLIENT_ID). It is not seeded: register it throughPOST /api/admin/clientswith grant typeclient_credentials, the scopedocuments.readand the audienceresource-server. -
Preconditions: Spring profile
client-credentialsonservice-client; a client authentication method the client is registered for (see Client authentication); forclient_secret_basic, the generated secret inSERVICE_CLIENT_SECRET. -
Endpoints:
POST /oauth2/token(authorization server),GET /api/documents(resource server).
Steps
-
ServiceClientApplicationstarts with theclient-credentialsprofile, which activatesClientCredentialsCli(aCommandLineRunner) and bindsapplication-client-credentials.yml:service-client.auth.method(SERVICE_CLIENT_AUTH_METHOD, defaultclient_secret_basic),client-id,client-secret,token-uri(SERVICE_CLIENT_TOKEN_URI, defaulthttp://localhost:9000/oauth2/token),scopes(SERVICE_CLIENT_SCOPES, defaultdocuments.read),refresh-before(SERVICE_CLIENT_REFRESH_BEFORE, defaultPT60S) andservice-client.resource-server.base-uri(SERVICE_CLIENT_RESOURCE_SERVER_URI, defaulthttp://localhost:8081). -
ServiceClientRegistrationMapperbuilds a Spring SecurityClientRegistrationwith the idservice-client, grant typeclient_credentialsand the configured authentication method;OAuth2ClientConfigurationkeeps it in anInMemoryClientRegistrationRepository. -
ClientCredentialsClirunsListDocumentsUseCase, which calls the domain portDocumentGateway, implemented byRestDocumentGatewayover the client generated from the resource server’s contract. -
Before the call, the interceptor built by
ResourceServerInterceptorsasks theAuthorizedClientServiceOAuth2AuthorizedClientManagerfor an authorized client. With no cached token, the client-credentials provider postsgrant_type=client_credentialsandscopeto/oauth2/tokenthrough theRestClientClientCredentialsTokenResponseClientthatTokenEndpointClientsconfigures (assertion, mutual TLS or DPoP headers are added there when enabled). -
The authorization server authenticates the client, checks the grant type and the scopes and issues a signed JWT (
IssuedTokenClaimssetsaudto the client’s configured audiences). No refresh token is issued for this grant. -
The token is stored in the
InMemoryOAuth2AuthorizedClientServiceand sent asAuthorization: Bearer(orDPoP, see Sender-constrained tokens) toGET /api/documents. -
The resource server validates the token (see Resource server token validation) and requires
SCOPE_documents.read. The documents are printed as JSON lines. -
On a later call the manager reuses the cached token while more than
refresh-beforeof 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 newclient_credentialsrequest before it is used. -
With
SERVICE_CLIENT_PRINT_ACCESS_TOKEN=true(service-client.cli.print-access-token)ClientCredentialsClialso prints the token, obtained throughServiceTokens.
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);
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. -
subis the client id;audis the list of the client’s configured audiences (default the client id, so registerresource-server);scopeholds the granted scopes. -
No
rolesand notenant:IssuedTokenClaimsadds them only to tokens that have a user. -
With
tls_client_authandcertificateBoundAccessTokens, the token carriescnf.x5t#S256; with DPoP,cnf.jktandtoken_type=DPoP.
How it is tested
-
e2e-tests:ClientCredentialsEndToEndITruns the packagedservice-clientjar against the packaged authorization and resource servers, once per authentication method and once with DPoP, and checkssubandcnf. -
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) andClientAuthenticationIT.
Further reading
-
Client credentials and service-to-service calls (feature page:
service-clientand the client authentication methods)