When Keycloak service accounts fit service-to-service authentication
When a backend job or microservice must call another API and no user is signing in, a Keycloak confidential client with service accounts enabled and the client credentials grant covers the need. The client authenticates with its own identity, Keycloak issues an access token for that client's service account user, and the calling service presents that token to the target API. Nothing in the flow waits for a person to log in, which is why this pattern suits scheduled jobs, queue workers and internal services that act on their own behalf.
The grant gives a service a narrow set of guarantees. The token identifies the client and its service account user, not a human, so audit logs and API authorization decisions see a machine identity. The grant issues no refresh token, so when the access token expires the service requests a new one using its client credentials rather than renewing a session. Anything that needs to act for a named employee, such as reading that person's mailbox or honoring their data permissions, belongs with user-delegated tokens from an authorization code flow instead. Confirm which identity your target APIs expect before choosing, because an API that enforces per-user rules cannot authorize a service account that has no user behind it.
Before you commit, list each calling service and the single action it performs against each target API. If a service needs only read access to one API, a client with that one role is easier to review than a shared client that can reach everything. Check whether any caller needs to act for a user at all, since mixing both patterns in one client usually makes token claims and audit trails harder to read. Confirm with your security team how client secrets or signed client assertions will be stored and rotated, because that choice determines how much operational work this pattern adds over time.
How the client credentials grant and service account user work
In the client credentials grant, a service has no user signing in. It is the client itself that proves its identity to Keycloak's token endpoint and asks for an access token. The request carries the grant type client_credentials along with the client identifier and a credential that proves the client's identity. Keycloak checks the credential, checks that the client is allowed to use this grant, and then returns an access token. The service then presents that token to the APIs it calls, and those APIs validate it the same way they validate any other Keycloak token.
- Request shape: The service posts a form to the realm's token endpoint with
grant_type=client_credentials, itsclient_id, and its authentication credential. - No browser step: There is no redirect, login page or consent screen, so the flow suits daemons, batch jobs and back-end services.
- No refresh token: The client requests a new access token when the old one expires instead of refreshing it.
- Client-level identity: The token identifies the client and the service account user behind it, not an individual person.
- Standards basis: The grant is part of OAuth 2.0, and the Keycloak server administration guide describes how Keycloak implements it.
Before going live, confirm the exact token request your client library sends, and test one request against a non-production realm to see the response fields your APIs will read.
When a client has service accounts enabled in Keycloak, Keycloak creates a hidden user that represents the client. This service account user has no password and no login screen. Its only purpose is to hold roles, so the access token issued to the client can carry permissions the same way a user token does. Because the user is tied to the client, deleting or disabling the client also removes that identity's access, which is useful for offboarding a retired service.
- What it is: A user record linked to one confidential client, created when service accounts are enabled on that client.
- Why it exists: Keycloak uses a user identity so that role mappings and token claims work the same way for services as for people.
- Lifecycle: The service account follows the client, so renaming, disabling or deleting the client changes its access immediately.
- Limits: It cannot log in interactively, so it should not be shared between unrelated services.
- One client, one identity: Give each service its own client rather than reusing a single client across several workloads.
Check that every production service has its own client and that no client exists only for convenience, since each one is an identity that can obtain tokens.
Permissions for a service are assigned to its service account user, not to the client directly. In the admin console, the service account roles are managed from the client's settings, where you can assign realm roles or client roles to the service account user. The roles you assign there become the roles that appear in the access token when the service requests one. What the token can do downstream depends on how the resource server reads those roles, so the assignment step is where least privilege begins.
- Where to look: Open the client, go to its service account roles tab, and assign realm roles or client roles.
- Client roles: Prefer client roles on the API the service calls, so that a permission for one API does not grant access to others.
- Client scopes: Scopes and protocol mappers control which claims the token includes, so review them alongside roles.
- Audit trail: Keep a written record of which roles each service holds and why, since the admin console shows the current state only.
- Least privilege: Start with no roles and add only what the service's API calls require.
Before release, decode a sample token and confirm that it contains the roles and audience you expect and nothing else.
How a service obtains and uses a token
The calling service starts by posting its client ID and credentials to the Keycloak token endpoint using the client credentials grant. Keycloak checks the credentials, issues an access token for the service account, and returns it along with its expiry. The service then sends that token as a bearer token to the target API, which validates it before responding. The service should cache the token and reuse it until shortly before expiry, instead of requesting a new one for every call. Check that the target API verifies the token's signature, issuer, audience and expiry on each request.
Client credentials flow from token request through API call and token reuse.
Client secret or signed JWT: which client authentication to choose
This table compares the client authentication options for a Keycloak service account client, covering when each fits, what you must store and rotate, and the operational trade-offs. Read each row against your own secret management and key management practices, and confirm which methods your Keycloak release supports before you commit to one.
| Method | When it fits | What you store and rotate | Operational trade-offs |
|---|---|---|---|
| Client secret | Smaller estates where each service can read one secret from a vault or orchestrator and rotation can be scheduled | A shared secret per client in Keycloak and in each calling service; rotate by issuing a new secret and updating consumers | Simple to set up and debug, but the secret travels with every caller and a leak requires rotation of that client; rotation must be coordinated across deployments |
| Signed JWT (private key JWT) | Estates with a security policy against shared secrets, or where services already manage asymmetric keys in a key store or HSM | A private key held by the service and a public key registered with the client in Keycloak; rotate by registering a new key and retiring the old one | No shared secret crosses the wire, but key generation, storage, rotation and clock skew on signed assertions add setup work; debugging signature errors takes more effort |
| Other methods listed in the Keycloak docs | Only where your release documents them and your identity policy requires them | Depends on the method; confirm the requirements in the server administration documentation for your release | Confirm supported methods, configuration keys and their defaults for your Keycloak version before designing around them |
| Secret or key storage | Applies to both methods | Use a secrets manager or key store with access logging and restricted read rights per service | Storage choice drives audit evidence and how quickly a compromised credential can be replaced |
| Rotation procedure | Applies to both methods | Document who issues the new credential, how services pick it up, and when the old one is disabled | Rehearse rotation before an incident; a rotation that requires a redeploy of every caller takes longer than expected |
Scoping roles so each service gets only what it needs
A service account is only as safe as the roles behind it. The decisions below set what each client can call, how roles are granted and how that access is reviewed over time. Work through them together, because a shared client or a broad default role undoes the narrower choices made elsewhere.
One client per service
Give each service its own confidential client with its own service account, instead of sharing one client across several workloads. A separate client means a leaked secret or a compromised workload exposes only that service's permissions, and it keeps audit trails readable. Check that no two deployments read the same client ID and secret from a shared configuration file.
Keycloak docsRealm roles versus client roles
Realm roles apply across the whole realm, so any client can be granted them and their meaning spreads. Client roles belong to one client and describe the API it protects. For service-to-service calls, prefer client roles defined on the target API's client so that a grant to one service cannot be read as access to another. Confirm which style your APIs check before you design role names.
Assign only the roles each call needs
List the endpoints each service calls on each target API, then grant only the matching client roles to that service account. Start from the narrowest set and add a role when a call fails in testing, not when a team asks for access in advance. Ask the owner of each API to confirm the list before it goes live.
Avoid shared default roles
Keycloak assigns default realm roles to new users and may apply default roles to clients by configuration, so a service account can inherit permissions no one chose on purpose. Review the default roles of the realm and remove any that grant API access. Treat a composite role that bundles several client roles as a shared default only if you have checked every member.
Review service account role mappings
Service account role mappings change over time as teams add features, so review them on a fixed schedule and after each release. Export the list of clients, their service account users and their assigned roles, then compare it with the endpoint inventory. Remove roles that no call path uses and record who approved each remaining grant.
Document which API each client may reach
Keep a register that maps each client ID to the APIs, audiences and roles it may use, and the owner who approved it. Resource servers can then check the audience and roles on each token against that register. Keep the register in version control next to the realm configuration so that changes go through review.
Caching tokens to limit load on Keycloak
Each service should request an access token once, keep it in memory, and fetch a new one shortly before it expires. Requesting a token for every outbound call turns Keycloak's token endpoint into a per-request dependency, adds latency to every call your services make, and multiplies load on the realm's database and signing keys as traffic grows. A small token cache inside the service client, keyed to the service account and the requested scope, avoids this. Most HTTP client libraries and OAuth 2.0 client libraries can hold the token and its expiry time, so the work is usually a configuration decision rather than a large build. Confirm with your library whether it refreshes tokens automatically or leaves that logic to your code.
The lifespan of the access token set on the client or realm determines how often the cache expires and how much traffic reaches the token endpoint. A longer lifespan means fewer token requests but a longer window in which a revoked or disabled service account keeps working, so the trade-off belongs in your security review alongside the access token policies in your realm. A very short lifespan is the opposite problem: if the refresh margin is larger than the lifespan, or the cache discards tokens early, every request can end up fetching a new token, and a fleet of pods doing this at once can generate a steady spike in token requests. Test the cache under realistic concurrency and watch token endpoint request counts in the Keycloak observability metrics before you settle on settings.
Plan for the case where a token request fails, because Keycloak is restarting, a network path is down, or a client secret has been rotated. Each service should retry with exponential backoff and jitter, cap the number of attempts, and keep serving from the still-valid cached token while it waits. Without these controls, many instances retrying at the same instant can overload Keycloak at the moment it is least able to recover. Also define what happens when the cached token expires during an outage: the service should fail its calls clearly and raise an alert rather than loop indefinitely. Ask your team to document these behaviors and test them with a deliberately unavailable token endpoint before production.
Setting up a service account client step by step
This sequence takes a Keycloak realm from an empty confidential client to a service that obtains its own access token and calls a target API. Each step ends with a check, so you can confirm the configuration before the next change builds on it.
Create a confidential client in the realm
In the admin console, open the realm that will issue tokens for this service and create a new client with a clear identifier that names the calling service, such as
billing-reporter. Keep the realm separate from end-user realms if your organization splits workforce and machine identity. Check that the client appears in the client list with its access type set to confidential, which means Keycloak will hold a secret or key for it and it cannot be used from a browser or mobile app.Enable client authentication and service accounts
On the client's capability settings, turn on client authentication so the client must prove its identity at the token endpoint. Then enable service accounts, which creates a hidden service account user tied to this client. Turn off standard flow and direct access grants unless a separate need exists, so the client can only use the client credentials grant. Confirm the setting by opening the Service account roles tab, which should now be visible for the client.
Choose the client authentication method
Decide how the service proves its identity. A client secret is the simpler option and is set on the Credentials tab, but it must be stored and rotated by your team. Signed JWT client authentication uses a key pair held by the service, so the private key never travels to Keycloak; configure the client's authenticator and register the public key or JWKS endpoint. Whichever you choose, record the decision and where the secret or private key is stored. The check is that the chosen method is the only one the client accepts.
Assign roles to the service account user
Open the Service account roles tab and assign only the client roles or realm roles the service needs to call the target API. Avoid assigning realm-admin or broad roles that exist for convenience. If the target API is another Keycloak client, assign roles from that client, not from the realm. Check the assignment by viewing the effective roles on the service account user, then confirm a role the service should not need, such as an administrative role, is absent.
Request a token with the client credentials grant
From a trusted host, send a POST request to the realm's token endpoint with
grant_type=client_credentials, the client ID, and either the client secret or a signed client assertion, depending on the method you chose. Keycloak returns an access token without any user present. Store the response in a secure place for testing only. The check is that the response includes anaccess_tokenand that itsexpires_invalue matches the lifespan your realm defines.Decode the token to confirm roles and audience
Decode the access token payload, for example with a JWT inspection tool, and read the
resource_accessorrealm_accessclaims and theaudclaim. The roles listed should match exactly what you assigned in the earlier step, and the audience should name the API the service will call. If a user-only role or an unexpected client role appears, return to the role assignments and remove it before continuing. Confirm the token contains nosubvalue that points to a human user account.Call the target API with the bearer token
Send a request to the target API with the header
Authorization: Bearerfollowed by the access token. The API should accept the token when the required role is present and reject it with an authorization error when the role is missing. Test both outcomes by calling one endpoint the service should reach and one it should not. The check is that the allowed call succeeds and the forbidden call fails, which confirms the API enforces the role model you configured in Keycloak.
Security and operational risks of machine credentials
Service accounts hold standing authority to call your APIs without a person in the loop, so their risk sits in how credentials are stored, rotated and observed. The cards below cover the controls that keep client secrets and signed keys contained, and the Keycloak settings that make token issuance visible.
Client secret storage and rotation
A client secret for a service account is a password that never expires unless you rotate it. Keep it in a secrets manager your platform controls, inject it at runtime, and never commit it to source control or container images. Confirm how your team will rotate it: Keycloak lets you regenerate a client secret, so plan a window where both old and new values are accepted by the services that call it.
Keycloak server admin docsPrivate key management for signed JWT
With signed JWT client authentication, the private key never leaves the calling service, which removes the shared secret from Keycloak's exposure. The risk moves to the key itself. Generate the key pair in a controlled place, restrict read access to the workload that signs assertions, record which public key is registered on the client, and define how you replace it before expiry.
TLS on all token traffic
Client credentials requests carry the client secret or a signed assertion in every call, so the token endpoint must be reached only over TLS. Keycloak's production guidance calls for TLS on all communication, including between your reverse proxy and the server where your architecture uses one. Check that services reject plain HTTP endpoints and that certificate validation is not disabled in client libraries.
Production configuration guideSeparate admin and public hostnames
Service accounts often reach Keycloak across networks you do not expose to the internet. The production guide advises serving the admin console and Administration REST API on a different hostname or context path from public frontend URLs, with a reverse proxy that restricts paths. Confirm which paths your public ingress forwards, and block the admin paths there so token requests and administrative access are controlled separately.
Audit and logging of token issuance
Every client credentials grant produces a token issuance event, but the events you can review depend on your event settings and logging configuration. Decide which client and admin events you need to keep, who can read them, and how long they are retained, then test that a token issued to a given service client shows up in your log pipeline. Ask your Keycloak team to confirm the event types available in your version.
Monitoring with Keycloak metrics
Keycloak exposes Prometheus-format metrics at /metrics on its management interface when started with --metrics-enabled=true, and optional HTTP request and cache histograms can be turned on. Use them to watch token request rates and error patterns from service clients, and alert when a service begins failing authentication after a rotation. Keep the management interface off public networks, since metrics reveal operational detail.
Questions teams ask before running service accounts in production
How much effort does it take to set up service accounts for many services?
Effort grows with the number of services and the number of distinct permission sets they need, more than with the Keycloak configuration itself. Creating one service account client is a small task. The larger work is deciding which roles each service needs, mapping those roles into tokens the APIs can check, and documenting each client so an owner can be named for it. Teams that already have a service inventory and API catalog spend less time on discovery. Ask any partner to break the quote into inventory, realm design, client configuration, API authorization checks, secret or key handling, testing and handover, and to state which parts are one-time and which recur as services are added or retired.
How long does a rollout take for a given number of services and APIs?
Duration depends on how many services call how many APIs, whether roles already exist, and how many services have hard-coded or shared credentials that must move. A rollout that covers a handful of services with clear owners usually moves faster than one that spans a large estate with unclear ownership. Timing is also set by change windows, security review and testing against each API. Keycloak itself does not set the timeline. Ask for a written schedule with milestones per service group, and confirm which services go first, since low-risk internal callers are a common starting point for a pilot.
What does the work need from our team?
You need named owners on three sides. Realm owners decide the client naming, token lifetimes and which realm the service accounts live in. API owners define which roles or scopes each endpoint requires and check tokens on their side. Secret or key management owners decide where client secrets or signing keys are stored, who can read them and how they are issued to workloads. Your platform team usually provides the deployment path for secrets, such as a vault or a Kubernetes secret store. Without these owners, rollouts stall on decisions about who may change a role or see a secret.
Can our own team set up service accounts without a partner?
Yes, if your team already runs Keycloak in production and has engineers who understand the OAuth 2.0 client credentials grant, token validation and secret storage. A small pilot with one or two services is a good way to test that. Partners add the most value when many services must move at once, when role design needs review across several API owners, or when security testing of the resulting setup is required. Whichever path you choose, agree on a written list of clients, roles and owners before anything is created, because that list becomes the basis for later audits and reviews.
How do we rotate client secrets or signing keys without an outage?
Rotation is a planned process rather than a one-time event. For client secrets, the usual approach is to issue a new secret, update the consuming service through your secret store, confirm the service is authenticating with the new value, and then retire the old one. For signed JWT client authentication, you register a new public key with the client, deploy the matching private key to the workload, and remove the old key after callers have switched. Confirm in your own Keycloak version how the client credentials are stored and how the admin console and API expose changes. Write a rotation schedule per client, assign an owner to each, and test the procedure on a non-production realm first.
Which parts of the setup recur after go-live?
The recurring work is operational rather than a single build. Each new service needs a client, a role decision and an owner. Each secret or key needs rotation on the schedule you set. Keycloak upgrades, which the project ships in minor and major releases, can change behavior, so the service account configuration and token caching in each consuming service should be retested after upgrades. Reviews of who holds which roles, and removal of clients for retired services, also recur. Ask any provider whether these tasks are included in a support retainer or handed over as runbooks, and what your team must keep doing on its own.
What are the main risks if service accounts are set up loosely?
The main risks are over-broad roles, shared secrets across services, long-lived credentials that nobody rotates, and tokens that are requested on every call without caching, which adds load to Keycloak. A service account with a wide admin role can change far more than the one API it was built to call. Shared secrets make it impossible to tell which workload performed an action. Ask how each client maps to one service, whether roles are checked at the API as well as in the token, and how token caching respects expiry so services neither overload Keycloak nor use stale tokens.
How DeployOpen scopes and delivers service account setups
DeployOpen plans and builds Keycloak service account clients inside your own infrastructure, so each service gets its own client, only the roles it needs, and a credential method your security team can review. Engagements are fixed-scope, with the scope, deliverables and timeline agreed in writing before work starts.
How we scope
- We inventory which services call which APIs and record the roles each caller needs today.
- We agree whether each client uses a client secret or signed JWT client authentication, and why.
- The written scope lists clients, realms, role mappings, token lifetimes, caching guidance and the tests included.
How we build
- We create one service account client per workload, with the client credentials grant enabled and no unused flows.
- We map narrow client roles to each API, avoiding broad realm roles that grant access beyond a caller's need.
- We configure signed JWT client authentication where requested and set up secret storage and rotation paths.
How we hand over
- You receive a client inventory with purpose, owner, granted roles, credential type and rotation approach for each client.
- We document how each service requests and caches tokens and which expiry and refresh behavior to expect.
- We walk your platform and security engineers through the configuration and the tests used to confirm least privilege.
How we support
- Ongoing support, upgrades and continuous testing are available as retainers after handover.
- We can retest service account permissions after new services, roles or Keycloak upgrades change the access model.
- Keycloak upgrades and credential rotation are scoped as separate written work so each change is planned and recorded.

