Keycloak Kubernetes service account authentication: when workloads should stop using client secrets
Platform teams often run pods that call Keycloak-protected APIs with a client secret stored in a Kubernetes Secret, and every secret then needs rotation, distribution and revocation by hand. In suitable setups, a pod's Kubernetes service account token can replace that secret, because Keycloak trusts the cluster as an external identity provider and exchanges the token for a Keycloak access token. The pattern fits workloads that run inside a cluster you control, call APIs owned by your organization, and can map cleanly to one service identity. It does not fit workloads outside the cluster, third-party software that only accepts a static secret, or clusters whose API server you cannot reach from Keycloak.
The feature is configured in the Keycloak client and its identity provider settings, not in Kubernetes alone. Keycloak must trust the cluster's token issuer and signing keys, and the client must accept tokens with the expected audience and a bounded lifetime. Kubernetes controls which service account a pod receives and how long its projected token lasts, so both sides must agree on the audience value and on which service accounts map to which Keycloak clients. Confirm your cluster's API server issuer URL, its ability to publish keys to Keycloak, and the Kubernetes version your platform supports against the Kubernetes authentication documentation before you commit to the design.
Before you remove a secret, decide who owns the mapping from service accounts to clients, and test one workload end to end, including token expiry and revocation when a service account is deleted. Keep the client secret in place until the new path works, because the two methods can coexist during a migration. Also decide how you will audit which workload obtained which token, since that record is what your security reviewers will ask for. Your team should verify each step in a non-production realm first, using a workload you can roll back quickly.
How a pod's service account token reaches Keycloak
The flow starts with a pod that mounts a projected service account token. The workload sends that token to the Keycloak token endpoint as a client assertion. Keycloak then fetches the cluster's OIDC discovery document and signing keys from the issuer, which is the trust boundary, and checks the signature, audience and subject before issuing an access token. Check each hand-off in this order when a token is rejected.
Trust flows from the cluster's OIDC issuer to Keycloak, which then issues tokens to the pod.
Which configuration option fits each workload pattern
A Keycloak client authenticated by a signed JWT treats the workload as a confidential client whose assertion is signed by the cluster's token issuer. Keycloak verifies the signature against the issuer's published keys and checks the audience and expiry before issuing tokens, so no shared secret is stored in the cluster or in Keycloak. This fits organizations that want to remove stored client secrets from the workload path and can keep issuer keys and trust settings under review. The trade-off is setup work: you must register the issuer, confirm which claims Keycloak accepts, and test rotation of the issuer keys, which are controlled by your cluster distribution rather than by you.
- Secret removal: the workload holds no long-lived credential to leak from a manifest or an environment variable.
- Issuer trust: every accepted issuer must be registered and reviewed, because a trusted issuer can mint assertions for any client it is mapped to.
- Claim checks: audience and expiry rules must be set explicitly so tokens minted for other services cannot be replayed to Keycloak.
- Key rotation: confirm with your distribution how issuer signing keys rotate and whether Keycloak picks up new keys without manual steps.
- Operator support: confirm whether the Keycloak version and deployment method you run support this client authentication path before committing to it.
Before adopting this option, check the issuer URL, audience and token lifetime your cluster actually issues against a test client.
A dedicated client per workload gives each application its own Keycloak client, its own scopes and its own mappers, so access to one workload never depends on another. This fits regulated environments where auditors expect each service to be traceable to its own identity and where workloads have different permissions. The cost is volume: every new workload needs a client, a review of its scopes and a place in your configuration as code, so this option grows with your service count. Teams that already manage clients through the Keycloak Operator can express each one as a KeycloakOIDCClient resource, which keeps the inventory reviewable.
- Isolation: a compromised or misconfigured workload affects only its own client and scopes.
- Audit trail: token events and logs map directly to one client, which simplifies investigations.
- Ongoing overhead: each client adds review, rotation and lifecycle work for the owning team.
- Configuration as code: the Operator's client resources or your own pipeline keep the inventory versioned and reviewable.
- Scaling limit: large fleets of short-lived pods may produce more clients than your governance process can review.
Before choosing this option, count the workloads that need Keycloak access and confirm who approves each new client.
Shared clients let several workloads, or several namespaces, use one Keycloak client, and Keycloak maps each incoming Kubernetes service account to a principal and its roles. This fits clusters with many similar, low-privilege workloads, where a per-workload client would add review work without adding meaningful isolation. The risk is that the shared client becomes a broad grant: any workload mapped to it inherits its scopes, so the mapping rules carry the authorization decision and need the same care as the client itself. Mapping should use the namespace and service account name explicitly, not patterns that could match unexpected identities.
- Lower inventory: one client covers many workloads, which reduces review and configuration effort.
- Mapping precision: match on both namespace and service account name, and document every mapping.
- Blast radius: a mistake in the shared client's scopes affects every mapped workload at once.
- Change control: mapping changes need the same approval as client changes, because they alter who gets access.
- Migration path: starting shared and splitting later is possible, but plan the split before the mapping grows.
Before adopting this option, list every service account that will map to the shared client and confirm that each one needs the same scopes.
Some workloads run outside the cluster, such as batch jobs on virtual machines, legacy systems or services in another cloud account. They cannot present a Kubernetes service account token that Keycloak trusts by default, so they need a fallback path. The fallback is usually a separately managed client with its own credential, which should be stored in a secrets system you control rather than in a manifest. This fits a small number of external callers that cannot adopt the cluster's identity, and it should be kept deliberately narrow so the fallback does not become the default path for new workloads.
- Separate trust: external workloads use a different client and credential, so their access stays distinct from in-cluster identities.
- Secret storage: keep the fallback secret in a managed secrets store with rotation and access logging.
- Narrow scope: grant only the scopes these callers need, and review them on a fixed schedule.
- Exit plan: record which external workloads could move into the cluster or onto federated identity later.
- Visibility: tag these clients so monitoring and audits can separate them from in-cluster traffic.
Before accepting an external workload, confirm that it cannot run in the cluster or present a federated identity instead.
Setting up Keycloak to trust a Kubernetes cluster's service accounts
This sequence takes a cluster from its OIDC issuer to a tested, one-client-per-service-account setup in Keycloak, so each workload gets short-lived tokens it can prove without a stored client secret.
Confirm the cluster's OIDC issuer and endpoints
The cluster owner confirms the service account issuer URL the API server advertises and the cluster's OpenID Connect discovery document, which lists the JSON Web Key Set (JWKS) used to verify token signatures. Keycloak must reach both endpoints over TLS from its own network, so check that path with a request from a Keycloak node, not from a workstation. The step is done when the discovery document returns the expected issuer value and the JWKS endpoint returns signing keys to Keycloak. Ask the cluster team to confirm how the API server is configured for service account issuance, since the Kubernetes authentication documentation covers the token and OIDC mechanisms this depends on.
Register the cluster issuer as a trusted identity source
In the target realm, the Keycloak administrator adds the cluster's issuer as a trusted source for client authentication, using the issuer URL and the discovery-based key configuration confirmed in the previous step. Keep this scoped to the realm that will hold the workload clients, and record who approved the trust relationship. The step is done when Keycloak shows the issuer as configured and its keys load without errors in the server log. Confirm the exact configuration screen and key-loading behavior in the Keycloak server administration guide for your version, because this is the area where configuration details change between releases.
Set the expected audience on projected tokens
The cluster team configures each workload's projected service account token with a specific audience value that names the Keycloak realm or client intended to accept it, and sets an explicit expiry shorter than the default where the platform allows. Keycloak will reject any token whose audience does not match what the client expects, so the audience value must be agreed in writing between both teams. The step is done when a test pod's mounted token decodes to the expected audience and expiry claims, and both values match the Keycloak client configuration. Ask the platform team to confirm which token lifetime options the cluster supports, as these settings vary by Kubernetes version.
Map each service account to one Keycloak client
Create one Keycloak client per workload identity, and bind it to a single Kubernetes service account by its subject value, which takes the form of the service account's namespace and name. Avoid sharing a client across service accounts, because each token then carries no distinct workload identity for audit or revocation. Keep a register that lists service account, namespace, Keycloak client and owning team. The step is done when a sample mapping resolves to exactly one client and an unmapped service account is refused. Confirm the subject format Keycloak expects for your configuration before you write the register, because a mismatch here causes silent authentication failures.
Test token acquisition for a mapped workload
From a pod running as a mapped service account, request a token from Keycloak's token endpoint using the projected token as the client assertion, with the expected audience. The test passes when Keycloak returns an access token for the correct client and the token's claims identify the expected service account. Run the same request with the token for another workload and confirm that Keycloak issues no token to the wrong client. Record the request, response and claims in the change record so the test can be repeated after upgrades on either side.
Test rejection of wrong audiences and unmapped accounts
Present tokens with an incorrect audience, an expired token and a token from a service account with no client mapping, and confirm that Keycloak rejects each one with an error and writes a failed-authentication event. This is the negative test that proves the trust boundary works, and a security reviewer will expect to see its output. The step is done when all three cases fail as designed and the events appear in the Keycloak event log or the metrics or logging pipeline the team uses. Check the observability configuration in the Keycloak metrics guide if you want authentication failures visible in your monitoring stack.
How token audience and expiry limit what a stolen token can do
The main defense against a stolen workload token is making it useless outside its intended context. A projected service account token carries an audience and an expiry that are set when the pod requests the token, so the audience must be chosen deliberately and checked on every use. Keycloak should accept only the audience it expects for this workload, meaning the value the Kubernetes identity provider configuration and the client mapping agree on. A token minted for another service, or for a generic default audience, should fail validation even if its signature is valid. Confirm in your Keycloak version how the audience check is configured and whether it is enforced for every client that uses this path.
Short lifetimes and a dedicated audience reduce replay risk in two different ways. A token that expires quickly leaves a smaller window in which copied credentials work, and a token scoped to one audience cannot be presented to other services that accept general Kubernetes tokens. Ask the platform team which expiration value the projected volume requests, since the kubelet refreshes the token before it expires and the exact limits and defaults depend on the Kubernetes version in use. Check the current behavior in the Kubernetes authentication documentation and confirm the Keycloak token lifetimes you configure for access tokens issued after the exchange.
Rotation of the projected token happens in the kubelet, not in application code. The kubelet rewrites the token file on the volume before expiry, so the workload only needs to re-read the file when it requests a new Keycloak token. Applications that cache the token value in memory for hours defeat this design, so the build should read the file at each token exchange. Plan a test that deletes or expires a pod's token in a staging cluster and confirms that the workload keeps authenticating after rotation and fails cleanly once the old token is rejected.
Security risks to design out before go-live
Keycloak trusts a Kubernetes service account token only as far as the cluster, the issuer configuration and the client mapping allow. The risks below sit in different layers, but they compound: a readable token, a loose audience and one shared client can turn a single pod compromise into access across several systems.
Secrets readable in etcd
Kubernetes stores Secrets unencrypted in etcd by default, so anyone who can read an etcd snapshot or backup can read stored credentials. Moving workloads to service account tokens removes long-lived client secrets, but any remaining Secrets, including Keycloak admin credentials and database passwords, still need protection. Check that encryption at rest is enabled for Secrets in the API server, that etcd backups are encrypted and access-controlled, and that the key management for encryption is separate from the cluster.
Secrets good practicesBroad RBAC allowing token reads
Any subject that can create a token for a service account, read Secrets or exec into pods can obtain the workload's identity. Review ClusterRoles and RoleBindings for wildcard verbs, cluster-wide Secret list and watch rights, and the pods/exec subresource. Confirm which users and CI pipelines can call the TokenRequest API for each service account, and remove default bindings that grant more than the workload needs.
Trusting the wrong issuer
Keycloak must accept tokens only from the issuer URL of the cluster you intend to trust. If the identity provider configuration points at a shared or test cluster, or at an issuer whose signing keys are not controlled by your platform team, a token minted elsewhere can be presented as a workload identity. Record the exact issuer, confirm the JWKS source matches the cluster, and keep one Keycloak identity provider per cluster so each trust decision is explicit.
Audience reuse across services
A token issued for one purpose can be replayed against another service if its audience is broad or the same for every consumer. Request tokens with a specific audience for Keycloak, and make sure the receiving service checks that audience value rather than accepting any valid token from the cluster. Set short expiry on projected tokens so a copied token has a limited useful life. Confirm both values in the design review, because the defaults differ between cluster configurations.
One powerful client for many workloads
Mapping several workloads to one Keycloak client gives every pod that client's scopes, roles and token lifetime. A compromised low-privilege pod then inherits the permissions of the most privileged workload behind it. Create one client per workload or per trust boundary, assign only the roles each client needs, and review client scopes and service account roles whenever a new workload is mapped.
Lost audit trail from shared identities
When many replicas or pods authenticate as the same identity, Keycloak event logs show the client, not the workload instance that acted. Investigations then cannot tell which deployment, namespace or pod made a request. Map workloads to distinct clients where the trust boundary requires it, record namespace and service account names in logs and claims, and confirm that Keycloak event logging and Kubernetes audit logging both retain entries long enough for your investigation process.
Operating the trust link across cluster upgrades and key changes
The trust link between a cluster and Keycloak keeps working only while two things stay true: Keycloak can fetch the cluster's current signing keys, and the token issuer URL and audience values in your configuration still match what the cluster issues. Both change during routine work. A cluster rebuild, a control plane certificate or key rotation, or a change to the issuer URL produces new keys or a new iss value, and a Keycloak identity provider configured against the old values will reject tokens that were valid the day before. Before you go live, write down where the issuer and key location are configured on both sides, who owns each change, and which change tickets must touch the Keycloak identity provider settings as well as the cluster.
Keycloak and Kubernetes move on separate cycles, so the trust link needs its own upgrade checklist. Keycloak plans four minor releases a year and a major release every two to three years, and its Operator documentation strongly recommends manual approval mode for operator updates. Kubernetes maintains the three most recent minor releases, and the version skew policy requires kube-apiserver to be upgraded one minor version at a time. Use the supported version windows on the Kubernetes release page to plan cluster upgrades, and confirm with your Keycloak distribution which minor versions are in scope for your support agreement. Each upgrade in either system should include a test that requests a token from the cluster, exchanges it at Keycloak, and checks the resulting roles and the audience the workload receives.
Treat token acquisition as a standing regression test rather than a one-time setup check. Run it from a test workload in a non-production cluster after each Keycloak minor upgrade, after each cluster upgrade, and after any key rotation, and alert on failures in production. Record the expected iss, aud and expiry values so a change shows up as a diff, not as a workload outage. Keep the service account token lifetime and the Keycloak token settings in your configuration repository so they are reviewed like any other change. Confirm the key refresh behavior for your Keycloak version and cluster configuration against the upstream documentation before relying on automatic refresh during a rotation window.
Limits to confirm in your environment
Using Kubernetes service account tokens as Keycloak client credentials depends on details that vary by Keycloak version, cluster provider and network layout. The cards below cover the checks that decide whether the design works as planned, and each one should be confirmed against vendor documentation and your own cluster before build work starts.
Supported client authentication method
Confirm that the Keycloak version you plan to run supports the Kubernetes-token client authentication method you intend to use, and check whether it needs a feature flag, a particular client authenticator or a specific configuration form. Keycloak's current release is 26.8.1, but the authenticator behavior should be read from the release documentation for your own version rather than assumed from a newer one. Check this before you pick the design, because a later upgrade can change how the method is configured.
Keycloak docsKeycloak reaching issuer and key endpoints
Keycloak must fetch the cluster's OpenID configuration and signing keys to validate tokens, so the Keycloak network path to the API server's issuer and JWKS endpoints has to be open. Confirm this from the Keycloak pods or hosts themselves, including DNS resolution, TLS trust for the cluster certificate authority and any egress policy or firewall between the two networks. A cluster reachable from your workstation is not proof that Keycloak can reach it.
Managed cluster issuer restrictions
Managed Kubernetes services control the token issuer, its audience settings and the API server flags that shape service account tokens, and they may not let you change them. Ask the provider which issuer URL the cluster uses, whether the issuer is publicly reachable or only private, and whether you can set the audience and expiry values you need. If the provider limits these settings, the design may need a different trust path or a self-managed cluster.
Workloads outside the cluster
Not every caller runs inside Kubernetes. Virtual machines, CI runners hosted elsewhere, partner systems and some legacy batch jobs will still need credentials that Kubernetes tokens cannot supply. List every client that will authenticate, then decide which ones keep a client secret or certificate, how those secrets are stored and rotated, and who owns them. Plan this mixed model before you retire any existing secrets.
Database and high availability effects
Client configuration changes are written to the Keycloak database and then seen by every node in the cluster. Confirm how your database and high availability design handle these writes, including which database you run, whether it is synchronously replicated across the sites you use, and how changes propagate during a failover. Test a client change in a non-production realm and confirm that all Keycloak nodes accept the new setting before you roll it out.
High availability overviewQuestions buyers ask before hiring help with this setup
What drives the effort of letting Kubernetes workloads sign in to Keycloak with service account tokens?
The main drivers are the number of clusters, the number of workloads that need a Keycloak client or identity, how many stored client secrets already exist and must be retired, and what your audit requirements demand as evidence. Each cluster adds an issuer to trust and a set of settings to verify. Each workload adds a mapping decision: which service account maps to which Keycloak client, and what roles or scopes it receives. Existing secrets add migration work, because workloads have to move without a gap in access. Audit requirements add documentation and evidence collection, such as showing which identities exist, how their tokens are scoped and how changes are reviewed. Ask any partner to size the work from these four inputs in writing before quoting.
Can our internal platform team set this up without outside help?
Often yes, if the team already runs Kubernetes and Keycloak in production and has someone who can read token claims and RBAC carefully. The work touches cluster authentication settings, Keycloak identity provider configuration, token audience and expiry, and workload mapping, so it crosses two teams that may not share habits. Outside help tends to make sense when the team lacks Keycloak administration experience, when many clusters must be handled consistently, or when the change must be reviewed by compliance or security staff who want an independent record. Check your bench against those three points before deciding.
What do we need to provide before the work can start?
Plan for four inputs: access to the Kubernetes clusters in scope with enough rights to read authentication configuration and inspect service accounts, administrative access to the Keycloak realm where clients will be created, network paths from Keycloak to each cluster's API server and issuer endpoint, and at least one test workload that can run in a non-production namespace. You should also name an owner for each cluster and each Keycloak realm who can approve changes. Confirm these items with your team at the start, because missing access is one of the most common causes of schedule slip.
How long does this kind of engagement take?
Duration depends on scope: how many clusters and workloads are involved, whether a Keycloak instance already exists and is in production, and how many stored client secrets must be replaced. A single cluster with one test workload and an existing Keycloak realm is a much smaller piece of work than a multi-cluster rollout with audit evidence requirements. No duration in this answer is a fixed commitment. Ask for a timeline that lists the phases, the cluster and workload counts it assumes, and the review points where your team signs off.
What recurring work follows go-live?
Once workloads authenticate with projected service account tokens, several items recur. Kubernetes releases come about three times per year on a cycle of about 14 weeks, and the project supports its three most recent minor releases, so the cluster authentication configuration has to be rechecked at each upgrade. Keycloak releases four minor versions a year under the project's plan, and the operator should be updated under manual approval, so the Keycloak side also needs a regular review. Client mappings need upkeep when teams add workloads or change namespaces, and access reviews should run on a schedule. Confirm with any provider which of these checks they perform and which stay with your team.
What does a fixed-scope DeployOpen engagement cover for this setup?
DeployOpen works from a written scope agreed before work starts. For this topic, that scope is typically defined by the clusters, Keycloak realms and workloads named in the agreement, along with the deliverables and timeline. DeployOpen plans and implements the Kubernetes identity configuration and Keycloak client mappings inside your infrastructure, prepares the documentation and evidence your security and compliance teams ask for, and tests the result. Ongoing support, upgrades and continuous testing are available as retainers after go-live. DeployOpen does not publish a price list, so a quote follows from the written scope.
Does the setup pass an audit once it is in place?
DeployOpen prepares systems, controls and evidence for compliance assessments, but it does not issue audit reports, attestations or certifications. Independent auditors and certification bodies make those determinations. What you can expect is a clear record of which identities exist, how tokens are scoped and expire, how mappings are reviewed, and where secrets were removed. Ask your auditor which evidence they want before implementation starts, so the setup produces it by design.
How DeployOpen scopes and delivers Keycloak workload authentication
DeployOpen plans, builds, tests and documents Keycloak client authentication with Kubernetes service account tokens inside your own clusters and identity estate. Work is agreed as a fixed scope in writing, so the Kubernetes identity provider setup, token audience and expiry rules, and workload-to-client mapping are reviewed before any configuration changes reach production.
How we scope
- We inventory the workloads that currently use stored client secrets and record which Keycloak clients they call.
- We confirm the Kubernetes distributions, API server issuer settings and Keycloak version the design must cover.
- The written scope names the clients, namespaces, audience values and token lifetimes that are in and out of the engagement.
How we build
- We configure the Kubernetes identity provider in Keycloak and set the expected issuer, audience and signing key handling.
- We map each service account to its own Keycloak client and role set, avoiding shared identities across workloads.
- We test token expiry, rejected audiences and revoked service accounts in a non-production environment before cutover.
How we hand over
- You receive the configuration as code, the mapping table of workloads to clients, and the test results.
- Runbooks cover rotating the API server signing keys, changing audiences and removing a workload's access.
- We document the secret removal steps so teams can confirm that no long-lived client secrets remain in use.
How we support
- Ongoing support, upgrades and continuous testing are available as a retainer, agreed separately from the fixed-scope build.
- Retainer work can cover Keycloak and Kubernetes version changes that affect token validation or the identity provider settings.
- Ask any partner to confirm how they handle issuer changes, cluster rebuilds and access reviews before you sign a quote.

