Skip to content
LF Cert Trainer

Lesson 70 · Section 7: Security

Lesson 70: Authentication: how the API server learns who you are

How every request to the API server gets an identity: users and service accounts, client certificates and bearer tokens, the static token file, anonymous requests, and how to tell a 401 from a 403 when access fails. · 18 min read · 4 min video

1/10Authentication
0:00 / 3:34

Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.

What authentication is

Everything in a cluster happens through the API server: kubectl, the kubelets, the controllers, the scheduler and every Pod that talks to Kubernetes all send it HTTPS requests. For each request the API server first has to answer one question: who is this? That step is authentication.

Authentication does not decide what you may do. It only turns a credential, such as a certificate or a token, into an identity. The next step, authorization, takes that identity and decides whether the request is allowed. You will meet authorization and RBAC later in this section.

Two questions for every requestHTTPSidentityproof rejectedno rule allows itRequestcert or tokenAuthenticationwho are you?Authorizationmay you do this?401 Unauthorizedno valid identity403 Forbiddenknown, not allowed
Two questions for every request. Authentication only answers who is calling. A request without a valid identity stops with 401. A request with an identity but no permission stops one step later with 403.

Parts:

  • Request (cert or token)
  • Authentication (who are you?)
  • Authorization (may you do this?)
  • 401 Unauthorized (no valid identity)
  • 403 Forbidden (known, not allowed)

Connections:

  • Request to Authentication: HTTPS
  • Authentication to Authorization: identity
  • Authentication to 401 Unauthorized: proof rejected
  • Authorization to 403 Forbidden: no rule allows it

The two steps fail in different ways, and telling them apart is the most useful skill in this lesson:

StatusMeaningWhat kubectl printsWhat to fix
401 UnauthorizedThe API server could not establish who you areerror: You must be logged in to the server (Unauthorized)The credential: token, certificate or kubeconfig
403 ForbiddenIt knows who you are, and you are not allowedError from server (Forbidden): ... User "alice" cannot list resource "pods" ...The permissions: a Role and a RoleBinding

A 403 message always names the user. If your name is in the error, authentication worked.

Who can authenticate

Kubernetes has two kinds of accounts, and they are managed in completely different ways.

Two kinds of accountsgetsproofruns assigned tokenHuman useraliceOutside sourceCA, OIDC, token fileAPI serverchecks the proofPodapp in the clusterServiceAccountobject in the API
Two kinds of accounts. A service account is an object in the cluster, and the cluster signs its tokens. A human user is not stored anywhere in Kubernetes: the API server only trusts a proof that something else issued.

Parts:

  • Human user (alice)
  • Outside source (CA, OIDC, token file)
  • API server (checks the proof)
  • Pod (app in the cluster)
  • ServiceAccount (object in the API)

Connections:

  • Human user to Outside source: gets
  • Outside source to API server: proof
  • Pod to ServiceAccount: runs as
  • ServiceAccount to API server: signed token
Human usersService accounts
Meant forPeople, and tools outside the clusterPods and other workloads
Stored in KubernetesNo. There is no User objectYes, a namespaced ServiceAccount object
Created withSomething outside the cluster: a certificate, a company login, a token filekubectl create serviceaccount
ProofClient certificate or bearer tokenA token signed by the cluster
UsernameWhatever the proof says, for example alicesystem:serviceaccount:<namespace>:<name>

The first row surprises most people. You cannot run kubectl create user, and kubectl get users returns an error. Kubernetes never stores human users. It trusts whatever a configured authenticator says about the request. If a certificate signed by the cluster's certificate authority says the caller is alice, then the caller is alice, even if nobody has ever mentioned that name to the cluster before.

Service accounts get their own lesson later in this section. Here you only need to know that they authenticate with a bearer token, like any other token user.

How it works

Authenticators turn a credential into an identity

The API server can run several authenticators at the same time. Each one understands one kind of credential.

From a credential to an identityClient certificateCN and O fieldsBearer tokenAuthorization headerNo credentialsnothing sentX.509 checksigned by cluster CAToken checksSA, static, OIDCAnonymoussystem:anonymousUser infoname, UID, groups
From a credential to an identity. Each kind of credential is checked by its own authenticator. Whichever one accepts the request, the result has the same shape: a username, a UID and a list of groups.

Parts:

  • Client certificate (CN and O fields)
  • Bearer token (Authorization header)
  • No credentials (nothing sent)
  • X.509 check (signed by cluster CA)
  • Token checks (SA, static, OIDC)
  • Anonymous (system:anonymous)
  • User info (name, UID, groups)

Connections:

  • Client certificate to X.509 check
  • Bearer token to Token checks
  • No credentials to Anonymous
  • X.509 check to User info
  • Token checks to User info
  • Anonymous to User info

A request is shown to the authenticators until one of them accepts it. The first to accept wins and the others are not asked. The documentation does not promise an order, so never design something that depends on which one runs first. If every authenticator that looked at a presented credential rejects it, the request ends with 401.

Whichever authenticator accepts, the result has the same four parts:

  • Username: a string such as alice, kubernetes-admin or system:kube-scheduler.
  • UID: an identifier that is meant to be more stable than the name. Often empty for certificate users.
  • Groups: a list of strings, such as dev or system:masters. RBAC can grant permissions to a whole group.
  • Extra fields: extra key and value pairs that some authenticators add.

Every authenticated request also gets the group system:authenticated added automatically.

The authenticators you will meet

AuthenticatorCredentialTurned on byTypical use
X.509 client certificatesA certificate signed by the cluster CA--client-ca-fileAdministrators and control plane components
Service account tokensA signed JSON Web Token--service-account-key-file, --service-account-issuerPods
Bootstrap tokensA short token stored as a Secret in kube-system--enable-bootstrap-token-authNodes joining with kubeadm join
Static token fileA token listed in a CSV file--token-auth-fileLearning and tests only
OpenID Connect (JWT)An ID token from an identity provider--authentication-config, or the older --oidc-* flagsCompany logins on real clusters
WebhookAny bearer token--authentication-token-webhook-config-fileAsking an outside service to check tokens
Authenticating proxyHeaders set by a trusted proxy--requestheader-* flagsThe aggregation layer, login proxies

For the CKA, the first four matter most. The next lessons cover certificates in depth, so here is only the rule that connects a certificate to an identity:

Subject: O = dev, O = qa, CN = alice

The common name (CN) becomes the username, and each organization (O) becomes a group. A certificate with that subject authenticates as user alice in groups dev and qa. Nothing else in the certificate matters for identity.

Bearer tokens

Service account tokens, bootstrap tokens, static tokens and OpenID Connect tokens are all sent the same way, in an HTTP header:

Authorization: Bearer a1b2c3d4e5f6

"Bearer" means that whoever holds the token is accepted as its owner. There is no second factor. Anyone who can read a token can use it, which is why tokens belong in Secrets and kubeconfig files with tight permissions, never in a Git repository or a ConfigMap.

The static token file

The static token file is the easiest authenticator to set up by hand, which makes it a good way to watch authentication work. It is a CSV file with at least three columns:

# token,user,uid,"group1,group2"
a1b2c3d4e5f6,alice,1001,"dev,qa"
f6e5d4c3b2a1,bob,1002

The fourth column is optional. With more than one group, the whole column must be in double quotes. You hand the file to the API server with --token-auth-file=<path>.

Its limits are the reason it is not used on real clusters:

  • The tokens sit on disk in clear text and never expire.
  • The file is read only when the API server starts. Adding, changing or removing a user means a restart.
  • There is no way to revoke one token other than editing the file and restarting.

Requests without credentials

A request that sends no certificate and no token is not rejected by authentication. It is given the username system:anonymous and the group system:unauthenticated, and then authorization decides. By default that identity may read only a few harmless paths such as /healthz, /livez, /readyz and /version, which is how load balancers can health-check an API server without credentials.

curl -k https://controlplane:6443/version          # works without credentials
curl -k https://controlplane:6443/api/v1/pods      # 403, User "system:anonymous"

Notice the second answer is 403, not 401: the anonymous user was authenticated, then refused. A request that does present a credential, and the credential is bad, gets 401 instead. Anonymous access can be switched off with --anonymous-auth=false, or limited to named paths in an AuthenticationConfiguration file.

Where it is configured on a kubeadm cluster

All of this is set with flags on kube-apiserver. On a kubeadm cluster the API server is a static Pod, so the flags are in /etc/kubernetes/manifests/kube-apiserver.yaml on the control plane node:

grep -E 'client-ca|token|service-account|anonymous|oidc|authentication' \
  /etc/kubernetes/manifests/kube-apiserver.yaml
    - --client-ca-file=/etc/kubernetes/pki/ca.crt
    - --enable-bootstrap-token-auth=true
    - --service-account-issuer=https://kubernetes.default.svc.cluster.local
    - --service-account-key-file=/etc/kubernetes/pki/sa.pub
    - --service-account-signing-key-file=/etc/kubernetes/pki/sa.key

That output tells you exactly which authenticators the cluster accepts: client certificates signed by /etc/kubernetes/pki/ca.crt, bootstrap tokens and service account tokens. No static token file and no OpenID Connect.

Under the hood · Groups that are built in

A few group and user names starting with system: have a fixed meaning:

  • system:authenticated: added to every request that passed authentication.
  • system:unauthenticated: the group of the anonymous user.
  • system:masters: members may do anything. The check happens before RBAC and cannot be taken away with a RoleBinding. On kubeadm clusters only the emergency file super-admin.conf uses it; the normal admin.conf is in the group kubeadm:cluster-admins, which gets its power from an ordinary ClusterRoleBinding.
  • system:serviceaccounts and system:serviceaccounts:<namespace>: every service account, and every service account of one namespace.
  • system:nodes: the kubelets, whose usernames are system:node:<node name>.
  • system:bootstrappers: nodes that are joining with a bootstrap token.

Because groups come from the credential, a certificate with O = system:masters is a master key that works until it expires. Kubernetes cannot revoke a single client certificate. Be careful what you sign.

Under the hood · Why real clusters use OpenID Connect

Certificates and static tokens share a weakness: you cannot take one back. A certificate is valid until its end date, and a static token is valid until someone edits a file and restarts the API server. Neither knows that an employee left the company last week.

With OpenID Connect, users log in at an identity provider and receive a token that lasts minutes or hours. The API server only needs the provider's address to verify the signature. Removing a person at the provider locks them out of every cluster as soon as their current token expires. Current Kubernetes versions configure this with a file passed through --authentication-config, which can list several providers and is reloaded when it changes; the older --oidc-* flags cannot be combined with it.

Using it

Example · Find out who you are

kubectl auth whoami asks the API server which identity it sees for your request:

kubectl auth whoami
ATTRIBUTE   VALUE
Username    kubernetes-admin
Groups      [kubeadm:cluster-admins system:authenticated]

The name and group come from the client certificate inside your kubeconfig. You can read the same values from the certificate itself:

kubectl config view --raw -o jsonpath='{.users[0].user.client-certificate-data}' \
  | base64 -d | openssl x509 -noout -subject
subject=O = kubeadm:cluster-admins, CN = kubernetes-admin

O is the group and CN is the username, exactly as the API server reported.

Example · Add a user with a static token file

This is for a practice cluster. Do it once and you will understand every other authenticator.

On the control plane node, create the file:

sudo mkdir -p /etc/kubernetes/auth
echo 'a1b2c3d4e5f6,alice,1001,"dev,qa"' | sudo tee /etc/kubernetes/auth/tokens.csv
sudo chmod 600 /etc/kubernetes/auth/tokens.csv

Then edit /etc/kubernetes/manifests/kube-apiserver.yaml. The API server runs in a container, so it needs the flag and a volume that makes the file visible inside the container:

spec:
  containers:
    - command:
        - kube-apiserver
        - --token-auth-file=/etc/kubernetes/auth/tokens.csv   # add
      volumeMounts:
        - name: auth                                          # add
          mountPath: /etc/kubernetes/auth
          readOnly: true
  volumes:
    - name: auth                                              # add
      hostPath:
        path: /etc/kubernetes/auth
        type: Directory

The kubelet notices the changed manifest and restarts the API server. Wait for it, then send a request as alice:

kubectl get nodes                                   # wait until this answers again
curl -sk https://localhost:6443/api/v1/namespaces/default/pods \
  -H "Authorization: Bearer a1b2c3d4e5f6"
{
  "kind": "Status",
  "status": "Failure",
  "message": "pods is forbidden: User \"alice\" cannot list resource \"pods\" in API group \"\" in the namespace \"default\"",
  "reason": "Forbidden",
  "code": 403
}

A 403 that names alice is success for this lesson: the API server knows who she is. She simply has no permissions yet. Change one character of the token and the answer becomes 401 Unauthorized.

Example · Use the token from kubectl

Add the token as a user in your kubeconfig, with a context that uses it:

kubectl config set-credentials alice --token=a1b2c3d4e5f6
kubectl config set-context alice --cluster=kubernetes --user=alice
kubectl --context=alice auth whoami
ATTRIBUTE   VALUE
Username    alice
UID         1001
Groups      [dev qa system:authenticated]

The username, UID and groups are the columns of the token file, plus system:authenticated. Listing Pods with this context still fails with Forbidden until a RoleBinding names alice or one of her groups.

Example · Authenticate as a service account

Service accounts are the one kind of account you can create with kubectl. Ask the cluster for a short-lived token and use it as a bearer token:

kubectl create serviceaccount ci
TOKEN=$(kubectl create token ci)                    # valid for one hour by default
kubectl --token="$TOKEN" --kubeconfig=/dev/null \
  --server=https://controlplane:6443 --insecure-skip-tls-verify auth whoami
ATTRIBUTE   VALUE
Username    system:serviceaccount:default:ci
Groups      [system:serviceaccounts system:serviceaccounts:default system:authenticated]

The username follows a fixed pattern that includes the namespace, and the groups let you grant permissions to all service accounts at once or to all of one namespace. --insecure-skip-tls-verify is acceptable for this quick test only; the KubeConfig lesson shows how to trust the cluster CA properly.

Example · Test another identity without its credentials

As an administrator you can ask the API server to treat your request as if someone else had sent it. This is called impersonation:

kubectl auth can-i list pods --as alice
kubectl auth can-i list pods --as alice --as-group dev
kubectl get pods --as system:serviceaccount:default:ci
kubectl auth whoami --as alice --as-group dev

Your own request is still authenticated first, and you need the impersonate permission, which cluster administrators have. Impersonation does not check that the user exists: there is nothing to check, because users are not stored. That makes it the fastest way to test RBAC rules for a user who has no certificate or token yet.

Tricks

Common mistakes

  • Looking for a User object. kubectl get users fails because the resource does not exist. Human users live in certificates, token files or an identity provider, never in the API.
  • Treating 401 and 403 as the same problem. A new RoleBinding cannot fix a bad token, and a new token cannot fix a missing RoleBinding.
  • Editing the token file and expecting it to work. The file is read once, at start. Restart the API server, for example by moving its manifest out of /etc/kubernetes/manifests and back.
  • Adding --token-auth-file without mounting the file. The API server runs in a container. Without a hostPath volume the path does not exist inside it, and the API server crash-loops.
  • Passing --token next to a kubeconfig that holds a client certificate. kubectl sends both, and the certificate usually wins, so you test the wrong identity. Use a separate context, or --kubeconfig=/dev/null as in the example above.
  • Putting a user in system:masters. That group skips authorization completely and the certificate cannot be revoked. Use a normal group and bind it to a ClusterRole.
  • Assuming authentication gives access. A brand new user who authenticates correctly can do almost nothing until authorization grants it.

Recap

  • Authentication turns a credential into an identity: username, UID and groups. It never decides permissions.
  • Human users are not objects in Kubernetes; service accounts are. Both end up as a username and groups.
  • The API server runs several authenticators at once: client certificates (CN is the user, O the groups), service account tokens, bootstrap tokens, the static token file, OpenID Connect. The first to accept wins.
  • No credentials means system:anonymous; bad credentials mean 401; a valid identity without rights means 403.
  • kubectl auth whoami shows who you are, and --as lets an administrator test any other identity.

Official docs

Quiz: check what you learned

5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.

Sign in to take the quiz and keep your score.

Discussion

Learners ask and answer questions here. Sign in to read and join the discussion.