The following methods are available for authenticating CI/CD pipelines in the Kubernetes API:


ServiceAccount

The ServiceAccount token is used directly for API authentication. No external IdP is required. For ServiceAccount, you can create long-lived tokens (without TTL, with the possibility of revocation or rotation) and short-lived tokens.

When multiple pipelines share a single ServiceAccount, audit logs will not contain information about specific pipelines.

Prerequisites

To configure token-based authentication for ServiceAccount, the following requirements must be met:

  • Cluster access with permissions to create ServiceAccounts and Secrets.
  • For external access: apiserver.publishAPI of the control-plane-manager module, or direct API access via VPN.

Create ServiceAccount and a long-lived token

To create a ServiceAccount and token, use the command:

d8 k create ns ci-deploy || true

cat <<EOF | d8 k apply -f -
apiVersion: v1
kind: ServiceAccount
metadata:
  name: gitlab-runner-deploy
  namespace: ci-deploy
---
apiVersion: v1
kind: Secret
metadata:
  name: gitlab-runner-deploy-token
  namespace: ci-deploy
  annotations:
    kubernetes.io/service-account.name: gitlab-runner-deploy
type: kubernetes.io/service-account-token
EOF

The kubernetes.io/service-account-token Secret type is a legacy approach. The recommended method is the TokenRequest API (d8 k create token ...).

Grant permissions

For details on granting permissions, see Granting permissions to users and service accounts.

Assign the necessary permissions to the ServiceAccount.

For the current role model, use ClusterAuthorizationRule:

cat <<EOF | d8 k apply -f -
apiVersion: deckhouse.io/v1
kind: ClusterAuthorizationRule
metadata:
  name: gitlab-runner-access
spec:
  subjects:
  - kind: ServiceAccount
    name: gitlab-runner-deploy
    namespace: ci-deploy
  accessLevel: Admin
  portForwarding: true
EOF

Available levels: User, PrivilegedUser, Editor, Admin, ClusterEditor, ClusterAdmin, SuperAdmin.

For the experimental role model, use ClusterRoleBinding:

cat <<EOF | d8 k apply -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: gitlab-runner-access
subjects:
- kind: ServiceAccount
  name: gitlab-runner-deploy
  namespace: ci-deploy
roleRef:
  kind: ClusterRole
  name: d8:manage:all:manager
  apiGroup: rbac.authorization.k8s.io
EOF

Get API URL and CA certificate

When using publishAPI:

  • When the API server is published via Ingress
  • When the API server is published via Gateway API (`alb`)

When the API server is published via Ingress, use the following commands:

API_HOST=$(d8 k -n kube-system get ingress kubernetes-api -o jsonpath='{.spec.rules[0].host}')
echo "API endpoint: https://${API_HOST}"

When the API server is published via Gateway API (the alb module), use the following commands:

API_HOST=$(d8 k -n kube-system get httproute kubernetes-api -o jsonpath='{.spec.hostnames[0]}')
echo "API endpoint: https://${API_HOST}"

If the API certificate is signed by a public CA (Let’s Encrypt), the --certificate-authority parameter is not required.

For a private CA (self-signed, the default mode — shared between both publication methods):

d8 k -n kube-system get secret kubernetes-api-ca-key-pair -o jsonpath='{.data.tls\.crt}' | base64 -d > /tmp/ca.crt

Create kubeconfig

Example of generating kubeconfig for a previously created ServiceAccount:

export CLUSTER_NAME=my-cluster
export USER_NAME=gitlab-runner-deploy
export CONTEXT_NAME=${CLUSTER_NAME}-${USER_NAME}
export FILE_NAME=kube.config

# For public CA, remove --certificate-authority and --embed-certs
d8 k config set-cluster $CLUSTER_NAME \
  --server=https://${API_HOST} \
  --certificate-authority=/tmp/ca.crt \
  --embed-certs=true \
  --kubeconfig=$FILE_NAME

d8 k config set-credentials $USER_NAME \
  --token=$(d8 k -n ci-deploy get secret gitlab-runner-deploy-token -o jsonpath='{.data.token}' | base64 -d) \
  --kubeconfig=$FILE_NAME

d8 k config set-context $CONTEXT_NAME \
  --cluster=$CLUSTER_NAME --user=$USER_NAME \
  --kubeconfig=$FILE_NAME

d8 k config use-context $CONTEXT_NAME --kubeconfig=$FILE_NAME

Short-lived tokens (TokenRequest)

The TokenRequest API allows creating tokens with limited lifetime. When creating such a token, specify the name of the ServiceAccount that needs to be granted access in the command (in the example — gitlab-runner-deploy):

d8 k create token gitlab-runner-deploy -n ci-deploy --duration=1h

The d8 k create token command itself requires access to the Kubernetes API. If the CI job has no initial cluster access, it cannot execute TokenRequest from within the job.

Usage patterns in CI

Bootstrap token with minimal permissions. CI stores a long-lived kubeconfig/token that only has permission to create TokenRequest for a specific ServiceAccount. At the start of the job, the bootstrap token issues a short-lived token used for deployment.

External token broker. An operator, secret manager (Vault, External Secrets), or external service periodically issues short-lived tokens and places them in CI variables or secrets. The CI job only consumes the ready token.

The bootstrap token should have minimal permissions: only create on the serviceaccounts/token resource for a specific ServiceAccount/namespace. Do not use cluster-admin. Limit the TTL of issued tokens and promptly revoke bootstrap access if compromised.

Usage without kubeconfig file:

export KUBE_SERVER="https://${API_HOST}"
export KUBE_TOKEN=$(d8 k create token gitlab-runner-deploy -n ci-deploy --duration=1h)
d8 k --server=$KUBE_SERVER --token=$KUBE_TOKEN get ns

Basic Auth

Authentication via username and password through IdP (LDAP, OIDC).

The password is sent to DP and validated through basic-auth-proxy/Dex.

Only one DexProvider in the cluster can have enableBasicAuth: true.

Prerequisites

The following requirements must be met to configure Basic Auth:

Enable

Add enableBasicAuth: true to DexProvider. For DexProvider configuration examples, see user-authn module documentation.

Get API endpoint

To get the API endpoint, use the command:

API_HOST=$(d8 k -n d8-user-authn get ingress kubernetes-api -o jsonpath='{.spec.rules[0].host}')
echo "https://${API_HOST}"

Verification

To check access, use the command:

curl -q -u "$K8S_USER:$K8S_PASSWORD" "https://${API_HOST}/version"

Possible errors:

  • 401 — invalid credentials or Basic Auth not enabled.
  • 403 — authentication succeeded but RBAC denies access.

Configure kubeconfig

Example of kubeconfig configuration for Basic Auth:

apiVersion: v1
kind: Config
clusters:
- name: my-cluster
  cluster:
    server: https://<API_HOST>
users:
- name: basic-auth-user
  user:
    username: "<USERNAME>"
    password: "<PASSWORD>"
contexts:
- name: default
  context:
    cluster: my-cluster
    user: basic-auth-user
current-context: default

Use in GitLab CI

Example of using Basic Auth in GitLab CI:

deploy:
  script:
    - d8 k --server="$K8S_SERVER" --username="$K8S_USER" --password="$K8S_PASSWORD" get ns

Variables K8S_SERVER, K8S_USER, K8S_PASSWORD are set in the project CI/CD settings.


Token Exchange

The pipeline obtains a token from the IdP, exchanges it at Dex for a token with aud=kubernetes, and uses it to access the API.

Recommended for GitLab CI and GitHub Actions.

DP/Dex does not receive the user password. How IDP_TOKEN is obtained depends on the IdP: OIDC job token (GitLab/GitHub) or IdP token endpoint (client_credentials).

Prerequisites

The following requirements must be met to configure Token Exchange:

Token exchange does not work with type: GitLab or type: GitHub connectors. Configure GitLab/GitHub as OIDC providers instead.

Create DexClient

To create DexClient, use the command:

cat <<EOF | d8 k apply -f -
apiVersion: deckhouse.io/v1
kind: DexClient
metadata:
  name: ci-token-exchange
  namespace: d8-user-authn
  annotations:
    dexclient.deckhouse.io/allow-access-to-kubernetes: "true"
spec: {}
EOF

The annotation dexclient.deckhouse.io/allow-access-to-kubernetes allows the client to request tokens with aud=kubernetes.

This grants cluster-wide access to the Kubernetes API. For this reason, adding the annotation or changing it to "true" requires access to modify the user-authn module configuration — such as the d8:manage:permission:module:user-authn:edit role. A namespace-level role that permits creating a DexClient is not enough: the admission-controller rejects the request with a message naming the annotation.

The addition of the annotation is restricted regardless of the specified value, including "false". This is required to ensure compatibility with previous DP versions where access has been granted when the annotation was present, regardless of its value.

This restriction is not applicable to an object, which already has the annotation assigned. Deletion and recreation of DexClient is treated as another addition of the annotation, so a GitOps controller that recreates the object instead of patching it requires the update permission on the moduleconfigs resource named user-authn.

Get client secret:

d8 k -n d8-user-authn get secret dex-client-ci-token-exchange -o jsonpath='{.data.clientSecret}' | base64 -d

client_id format: dex-client-ci-token-exchange@d8-user-authn.

Get Dex and API URLs

To get the Dex URL and API, use the following commands:

DEX_HOST=$(d8 k -n d8-user-authn get ingress dex -o jsonpath='{.spec.rules[0].host}')
API_HOST=$(d8 k -n d8-user-authn get ingress kubernetes-api -o jsonpath='{.spec.rules[0].host}')

Grant RBAC

DP configures kube-apiserver to validate Dex tokens. The email and groups claims from the token are used for RBAC.

The set of claims required by kube-apiserver for authentication depends on configuration. If kube-apiserver requires the name claim, add the profile scope.

For details on granting permissions, see Granting permissions to users and service accounts.

For the current role model, use ClusterAuthorizationRule:

cat <<EOF | d8 k apply -f -
apiVersion: deckhouse.io/v1
kind: ClusterAuthorizationRule
metadata:
  name: ci-deployer
spec:
  subjects:
  - kind: User
    name: deployer@example.com
  accessLevel: Admin
EOF

For the experimental role model, use ClusterRoleBinding:

cat <<EOF | d8 k apply -f -
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: ci-deployer
subjects:
- kind: User
  name: deployer@example.com
  apiGroup: rbac.authorization.k8s.io
roleRef:
  kind: ClusterRole
  name: d8:manage:all:manager
  apiGroup: rbac.authorization.k8s.io
EOF

Token exchange request

Example of a token exchange request:

RESPONSE=$(curl -q -s -X POST "https://${DEX_HOST}/token" \
  -u "${DEX_CLIENT_ID}:${DEX_CLIENT_SECRET}" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
  -d "subject_token=${IDP_TOKEN}" \
  -d "subject_token_type=urn:ietf:params:oauth:token-type:id_token" \
  -d "connector_id=${CONNECTOR_ID}" \
  -d "scope=openid profile email groups audience:server:client_id:kubernetes" \
  -d "requested_token_type=urn:ietf:params:oauth:token-type:id_token")

DEX_TOKEN=$(echo "$RESPONSE" | jq -r '.access_token')

Parameters:

  • subject_token — token from IdP
  • subject_token_type — id_token (GitLab/GitHub) or access_token (Keycloak)
  • connector_id — metadata.name of the DexProvider resource
  • scope — must include audience:server:client_id:kubernetes and profile

The expected audience is always kubernetes. If the API returns 401 with an audience mismatch error, verify that the scope includes audience:server:client_id:kubernetes.

GitLab CI

Example of a token request for GitLab CI:

deploy:
  id_tokens:
    GITLAB_OIDC_TOKEN:
      aud: https://<DEX_HOST>/
  script:
    - |
      RESPONSE=$(curl -q -s -X POST "https://${DEX_HOST}/token" \
        -u "${DEX_CLIENT_ID}:${DEX_CLIENT_SECRET}" \
        -H "Content-Type: application/x-www-form-urlencoded" \
        -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
        -d "subject_token=${GITLAB_OIDC_TOKEN}" \
        -d "subject_token_type=urn:ietf:params:oauth:token-type:id_token" \
        -d "connector_id=gitlab" \
        -d "scope=openid profile email groups audience:server:client_id:kubernetes" \
        -d "requested_token_type=urn:ietf:params:oauth:token-type:id_token")
      DEX_TOKEN=$(echo "$RESPONSE" | jq -r '.access_token')
      d8 k --server="${K8S_SERVER}" --token="${DEX_TOKEN}" auth whoami

Keycloak

Get token from Keycloak:

KEYCLOAK_TOKEN=$(curl -q -s -X POST "https://<KEYCLOAK_HOST>/realms/<REALM>/protocol/openid-connect/token" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=client_credentials" \
  -d "client_id=<KEYCLOAK_CLIENT_ID>" \
  -d "client_secret=<KEYCLOAK_CLIENT_SECRET>" | jq -r '.access_token')

Exchange at Dex (for Keycloak, use subject_token_type=access_token):

For access_token exchange, DexProvider requires getUserInfo: true.

RESPONSE=$(curl -q -s -X POST "https://${DEX_HOST}/token" \
  -u "${DEX_CLIENT_ID}:${DEX_CLIENT_SECRET}" \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=urn:ietf:params:oauth:grant-type:token-exchange" \
  -d "subject_token=${KEYCLOAK_TOKEN}" \
  -d "subject_token_type=urn:ietf:params:oauth:token-type:access_token" \
  -d "connector_id=keycloak" \
  -d "scope=openid profile email groups audience:server:client_id:kubernetes" \
  -d "requested_token_type=urn:ietf:params:oauth:token-type:id_token")

DEX_TOKEN=$(echo "$RESPONSE" | jq -r '.access_token')
d8 k --server="https://${API_HOST}" --token="${DEX_TOKEN}" auth whoami

Diagnostics

Use d8 k auth whoami to verify which identity is being used.

--token flag may not work — kubeconfig with auth-provider, exec, or tokenFile overrides the token from the flag. Use -v=8 for debugging:

d8 k --server="https://${API_HOST}" --token="${DEX_TOKEN}" auth whoami -v=8

The output shows which Authorization header is sent. For reliable token usage, use a minimal kubeconfig with only server and token, without auth-provider/exec.

Dex 400 — invalid subject_token, subject_token_type, or connector_id.

Dex 401 — invalid client credentials or invalid subject token.

API 401 — token validation failed. Check:

  • Annotation dexclient.deckhouse.io/allow-access-to-kubernetes on DexClient. If it is gone, check whether the admission-controller rejected the request that was supposed to add it, or whether a GitOps controller recreated the object without it: only a subject allowed to update the user-authn ModuleConfig may add the annotation.
  • Scope contains audience:server:client_id:kubernetes and profile.
  • Time synchronization between CI runner and cluster.

API 403 — authentication succeeded but RBAC does not allow access for the user or group from the token.

Decode token to check claims:

echo "${DEX_TOKEN}" | cut -d. -f2 | base64 -d 2>/dev/null | jq .

Additional resources