RealmDeployDocs
GuidesSingle sign-on for apps

Keycloak SSO for Kubernetes

Let kubectl users sign in to a Kubernetes cluster with Keycloak, map Keycloak groups to RBAC, and see what EKS and AKS let you configure.

The Kubernetes API server can accept ID tokens from Keycloak. Users run kubectl as usual; the kubelogin plugin (kubectl oidc-login) opens the browser, gets a token from Keycloak and hands it to kubectl. The API server checks the token's signature, issuer and audience, and RBAC decides what the user may do.

Checked against Kubernetes 1.37 docs, kubelogin 1.36.4 and Keycloak 26.8 on 25 November 2026.

Replace auth.example.com with your RealmDeploy hostname and acme with your realm.

You configure this on the API server itself. On clusters where you run the control plane (kubeadm and similar), you can. Most managed clusters do not let you set API server flags or files; see Managed clusters for what EKS and AKS offer instead.

In Keycloak

Create the client

kubelogin runs on each user's machine and cannot keep a secret, so the client is public and uses PKCE.

Open Clients, choose Create client, and use these values:

SettingValue
Client typeOpenID Connect
Client IDkubernetes
Client authenticationOff
Authentication flowStandard flow only
Root URLLeave empty
Valid redirect URIshttp://localhost:8000 and http://localhost:18000
Valid post logout redirect URIsLeave empty
Web originsLeave empty

kubelogin listens on port 8000, or 18000 if 8000 is taken, so both are listed. After Save, open the client's Settings tab and under Capability config set PKCE Method to S256. kubelogin uses PKCE automatically when Keycloak offers it.

To let users sign in from a machine without a browser, also turn on OAuth 2.0 Device Authorization Grant in Capability config and use kubelogin's --grant-type=device-code.

Add a groups claim

The API server reads groups from the ID token.

  1. On the kubernetes client, open the Client scopes tab and choose kubernetes-dedicated.
  2. Choose Configure a new mapper and pick Group Membership.
  3. Fill it in and choose Save:
FieldValue
Namegroups
Token Claim Namegroups
Full group pathOff
Add to ID tokenOn

Create the groups under Groups, for example k8s-admins and k8s-viewers, and add users to them.

An ID token from this client then looks like this. Its aud is the client ID, which the API server checks:

{
  "iss": "https://auth.example.com/realms/acme",
  "aud": "kubernetes",
  "preferred_username": "jane",
  "groups": ["k8s-admins"]
}

On the API server

There are two ways to configure it. Use one, not both: if the API server gets --authentication-config together with any --oidc-* flag, it reports an error and exits.

Structured authentication configuration is stable since Kubernetes 1.34 and uses apiserver.config.k8s.io/v1. The API server reloads the file when it changes, and the file can hold several issuers, several audiences and CEL rules.

/etc/kubernetes/auth/authentication-config.yaml
apiVersion: apiserver.config.k8s.io/v1
kind: AuthenticationConfiguration
jwt:
  - issuer:
      url: https://auth.example.com/realms/acme
      audiences:
        - kubernetes
    claimMappings:
      username:
        claim: preferred_username
        prefix: "oidc:"
      groups:
        claim: groups
        prefix: "oidc:"
    userValidationRules:
      - expression: "!user.username.startsWith('system:')"
        message: "username cannot use the reserved system: prefix"

Start kube-apiserver with:

--authentication-config=/etc/kubernetes/auth/authentication-config.yaml

On kubeadm, the API server runs as a static pod from /etc/kubernetes/manifests/kube-apiserver.yaml. Add the flag there and mount the file's directory into the pod as a hostPath volume, or the API server cannot read it.

FieldMeaning
issuer.urlYour realm. Must match the token's iss exactly. The API server fetches /.well-known/openid-configuration under it for the signing keys.
issuer.audiencesThe client ID. One entry must match the token's aud.
claimMappings.usernameThe Kubernetes username. preferred_username with the prefix oidc: gives oidc:jane.
claimMappings.groupsThe Kubernetes groups. The prefix gives oidc:k8s-admins.
userValidationRulesOptional CEL checks on the final user.

If you use email as the username claim, the API server rejects tokens whose email_verified claim is false, so users need a verified email in Keycloak.

Command-line flags

The older --oidc-* flags do the same for one issuer:

--oidc-issuer-url=https://auth.example.com/realms/acme
--oidc-client-id=kubernetes
--oidc-username-claim=preferred_username
--oidc-username-prefix=oidc:
--oidc-groups-claim=groups
--oidc-groups-prefix=oidc:

Without --oidc-username-prefix, a username claim other than email gets the issuer URL and # in front of it. RS256, Keycloak's default signing algorithm, is also the flags' default.

Groups and roles

Bind Kubernetes roles to the prefixed group names:

oidc-rbac.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: oidc-k8s-admins
subjects:
  - kind: Group
    name: "oidc:k8s-admins"
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: cluster-admin
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: oidc-k8s-viewers
subjects:
  - kind: Group
    name: "oidc:k8s-viewers"
    apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: view
  apiGroup: rbac.authorization.k8s.io

Apply it with an admin credential you already have: kubectl apply -f oidc-rbac.yaml. For access to one namespace, use a RoleBinding in that namespace instead.

Set up kubectl with kubelogin

Install kubelogin on each user's machine:

# Homebrew (macOS and Linux)
brew install kubelogin

# Krew (macOS, Linux, Windows and ARM)
kubectl krew install oidc-login

Check the login and see the claims Keycloak sends:

kubectl oidc-login setup \
  --oidc-issuer-url=https://auth.example.com/realms/acme \
  --oidc-client-id=kubernetes

Then add a user to the kubeconfig and use it:

kubectl config set-credentials oidc \
  --exec-interactive-mode=Never \
  --exec-api-version=client.authentication.k8s.io/v1 \
  --exec-command=kubectl \
  --exec-arg=oidc-login \
  --exec-arg=get-token \
  --exec-arg=--oidc-issuer-url=https://auth.example.com/realms/acme \
  --exec-arg=--oidc-client-id=kubernetes

kubectl config set-context --current --user=oidc

The kubeconfig entry this writes looks like this, and you can share it with your team:

~/.kube/config (users section)
users:
  - name: oidc
    user:
      exec:
        apiVersion: client.authentication.k8s.io/v1
        command: kubectl
        args:
          - oidc-login
          - get-token
          - --oidc-issuer-url=https://auth.example.com/realms/acme
          - --oidc-client-id=kubernetes
        interactiveMode: Never

kubelogin caches the ID token and refresh token, and refreshes the ID token when it expires. Add --token-cache-storage=keyring to keep the cache in the system keyring instead of on disk.

Managed clusters

Most managed services run the API server for you, so you cannot add --oidc-* flags or an authentication configuration file. What we could verify on 25 November 2026:

ServiceWhat you can do
Amazon EKSAssociate an OIDC identity provider with the cluster, in the console (cluster → Access tab → OIDC Identity Providers → Associate Identity Provider) or with eksctl associate identityprovider. You set the issuer URL, client ID, username and groups claims and prefixes, and required claims: the same settings as the --oidc-* flags. Clusters on Kubernetes 1.32 or later take up to 10 providers. The issuer must be reachable from the internet and must not use a self-signed certificate.
Azure AKSStructured authentication with JWT authenticators, in preview: register the JWTAuthenticatorPreview feature, then az aks jwtauthenticator add with a JSON file in the shape of one jwt entry above. Every mapped username and group must start with aks:jwt:. Microsoft's docs say previews are not meant for production. Needs the aks-preview CLI extension and Kubernetes 1.30 or later.

For other managed services, look for "OIDC identity provider" or "structured authentication" in your provider's docs.

EKS example

associate-identity-provider.yaml
apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig
metadata:
  name: my-cluster
  region: us-east-1
identityProviders:
  - name: keycloak
    type: oidc
    issuerUrl: https://auth.example.com/realms/acme
    clientId: kubernetes
    usernameClaim: preferred_username
    usernamePrefix: "oidc:"
    groupsClaim: groups
    groupsPrefix: "oidc:"
eksctl associate identityprovider -f associate-identity-provider.yaml

The cluster shows UPDATING for a few minutes while EKS applies it. Do not use system: in either prefix. The RBAC bindings and kubelogin setup above work unchanged.

AKS example

jwt-config.json
{
  "issuer": {
    "url": "https://auth.example.com/realms/acme",
    "audiences": ["kubernetes"]
  },
  "claimMappings": {
    "username": {
      "expression": "'aks:jwt:' + claims.preferred_username"
    },
    "groups": {
      "expression": "has(claims.groups) ? dyn(claims.groups).map(g, 'aks:jwt:' + g) : []"
    }
  }
}
az aks jwtauthenticator add \
  --resource-group my-resource-group \
  --cluster-name my-cluster \
  --name keycloak \
  --config-file jwt-config.json

Keycloak sends groups as a list, so the expression maps over it directly; dyn() tells CEL to treat the claim as a list. With this mapping, bind RBAC to aks:jwt:k8s-admins instead of oidc:k8s-admins.

Test it

  1. Run kubectl get nodes. kubelogin opens the browser at http://localhost:8000 and sends you to Keycloak.
  2. Before any binding exists, a signed-in user gets Forbidden ... User "oidc:jane" cannot list resource "nodes". That means authentication worked and RBAC is next.
  3. After the binding, kubectl auth whoami shows the username and groups the API server sees, for example oidc:jane and oidc:k8s-admins.
  4. To sign in again, run kubectl oidc-login clean. It deletes the token cache. If the browser still has a Keycloak session, you are signed in without a password.

Common errors

ErrorCauseFix
error: You must be logged in to the server (Unauthorized)The API server rejected the token: wrong issuer, wrong audience, or the API server cannot reach the discovery document.The issuer must be exactly https://auth.example.com/realms/acme, with no trailing slash, and the audience kubernetes. Compare with the token in the JWT claims validator. Check the API server log.
Forbidden for a user in the right groupThe group in the binding has no prefix, or Full group path is on and the claim says /k8s-admins.Bind to oidc:k8s-admins, turn off Full group path, and check with kubectl auth whoami.
Invalid parameter: redirect_uri in the browserkubelogin used a port that is not in Valid redirect URIs.List both http://localhost:8000 and http://localhost:18000, or set --listen-address and add that port. Check with the redirect URI matcher.
unauthorized_client with --grant-type=device-codeThe device grant is off on the client.Turn on OAuth 2.0 Device Authorization Grant. Look up other codes in the OAuth error lookup.
API server exits at startBoth --authentication-config and --oidc-* flags are set.Keep one of them.
Username is https://auth.example.com/realms/acme#jane--oidc-username-prefix is not set.Set it, for example to oidc:.

FAQ

Why the ID token and not the access token?

The Kubernetes OIDC authenticator uses the id_token from the token response as the bearer token. Its aud is the client ID, so no Audience mapper is needed.

Can I revoke a user's access right away?

Not the token itself: the API server checks it without calling Keycloak, so a token stays valid until it expires. Remove the user from the group or disable them in Keycloak, and they lose access when the ID token expires and kubelogin cannot refresh it. Keep the realm's token lifespans short.

Does the Kubernetes Dashboard sign in this way too?

Not by itself. Kubernetes' docs say the dashboard needs kubectl proxy or a reverse proxy that adds the id_token.

Sources

On this page