Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 37 ยท OAuth2 and OIDC Flows

Client Credentials Grant and Service Accounts in Keycloak

Secure machine-to-machine calls with the client credentials grant: service account clients, secrets versus signed JWT authentication, roles, caching tokens and rotating credentials.

Not every caller is a person. A nightly report job, a microservice or a deployment pipeline needs to call an API, and there is no user to log in. For these machine-to-machine cases OAuth 2.0 has the client credentials grant: the application proves who it is with its own credentials and receives an access token that represents the application itself. In Keycloak the identity behind that token is a service account.

How it works

sequenceDiagram
  participant J as Backend job (client)
  participant K as Keycloak
  participant A as API (resource server)
  J->>K: POST /token grant_type=client_credentials + client authentication
  K->>J: access token (no refresh token, no ID token)
  J->>A: GET /invoices  Authorization: Bearer token
  A->>A: validate signature, iss, aud, roles
  A->>J: 200 data

One round trip to Keycloak, then calls to the API until the token expires.

There is no browser, no redirect, no login form and no refresh token (the client can simply authenticate again).

Create a service account client

  1. Clients > Create client: OpenID Connect, Client ID report-job.
  2. In Capability config turn Client authentication On and Service accounts roles On. Turn Standard flow and Direct access grants Off: this client never has users.
  3. Save. Open the Credentials tab: choose the Client Authenticator and copy the secret.
  4. Open Service accounts roles tab. Here you assign roles to the service account user, a special user named service-account-report-job. Give it only the roles the job needs, for example the client role invoice-api: read.

The service account is a real user record in the realm, which means you can also give it attributes and group membership, and it appears in the user list (filtered by default).

Request a token

Terminal
curl -s -X POST http://localhost:8080/realms/demo/protocol/openid-connect/token \
  -u report-job:"$CLIENT_SECRET" \
  -d grant_type=client_credentials

-u sends HTTP Basic authentication (client_secret_basic); alternatively send client_id and client_secret in the form body (client_secret_post). The response:

JSON
{ "access_token": "eyJ...", "expires_in": 300, "refresh_expires_in": 0,
  "token_type": "Bearer", "not-before-policy": 0, "scope": "profile email" }

Decode the token and you will see azp: report-job, clientId: report-job, preferred_username: service-account-report-job and realm_access/resource_access for the service account's roles. The sub is the service account user's ID.

Ask for specific scopes with -d scope=invoices:read to narrow the token.

Client authentication methods

Method How the client proves itself When to use
Client Id and Secret A shared secret (Basic or POST) Simple, common; rotate regularly
Signed Jwt with Client Secret Client signs a short assertion with the shared secret (client_secret_jwt) Avoids sending the raw secret
Signed Jwt Signs with its private key; Keycloak holds the public key or JWKS URL (private_key_jwt) Strongest: no shared secret to leak
X509 certificate Mutual TLS with a client certificate High-security environments

Choose in Credentials > Client Authenticator. With private_key_jwt the client sends client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer and a client_assertion JWT whose iss and sub are the client ID and whose aud is the token endpoint.

Using the token well

  • Cache it until shortly before exp; do not request a token for every API call. Token requests hit Keycloak's database and rate limits.
  • Scope it: the service account should hold only needed roles; use Full scope allowed off and an audience mapper so the token works for just one API.
  • Treat the secret like a password: store it in a secret manager, load from the environment, never in source control or container images.
  • Rotate: Credentials > Regenerate. For zero downtime, create a second client for the new deployment, or use the client secret rotation client policy, which keeps the old secret valid during a grace period.

A token cache with proactive refresh (stand-in)

This runnable stand-in is a cache that fetches a fake token, reuses it, and renews it before expiry. It talks to a fake "Keycloak" function and counts calls, so you can see why caching matters.

Node.js Stand-in: cache machine tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Build a signed client assertion (stand-in)

private_key_jwt replaces the shared secret with a signature. This block builds the claims and signs an assertion with a freshly generated key, then verifies it as Keycloak would with the registered public key. The key is a demo key.

Node.js Stand-in: private_key_jwt assertion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Common mistakes

  • Enabling Service accounts roles on a client that also has Standard flow with a wildcard redirect.
  • Giving the service account the realm-admin role "to make it work". Grant exact roles.
  • Hard-coding the client secret in code or a Docker image layer.
  • Calling the token endpoint on every request and being rate-limited or slowing Keycloak.
  • Using a service account when a user's identity is needed for auditing; then pass the user token (or use token exchange).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which Keycloak setting makes a client able to use the client credentials grant?

    The client must authenticate itself and have a service account user.
  2. 2. Does the client credentials response include a refresh token?

    There is no user session to keep alive, so no refresh token is issued.
  3. 3. Which client authentication method avoids sharing a secret with Keycloak?

    With private_key_jwt Keycloak only stores a public key or a JWKS URL.
  4. 4. How should a service avoid overloading Keycloak?

    One token serves many calls until exp; renew slightly early.

Summary

  • Client credentials is for machine-to-machine access with no user; the identity is a service account.
  • Enable Client authentication and Service accounts roles, disable user flows, assign least-privilege roles.
  • Authenticate with a secret, or better a signed JWT or private key.
  • Cache tokens, scope them to one audience, rotate secrets and store them in a secret manager.
  • There is no refresh token; the client authenticates again.

Next: Scopes and Protocol Mappers