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
Official competencies this lesson covers
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.
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:
| Status | Meaning | What kubectl prints | What to fix |
|---|---|---|---|
401 Unauthorized | The API server could not establish who you are | error: You must be logged in to the server (Unauthorized) | The credential: token, certificate or kubeconfig |
403 Forbidden | It knows who you are, and you are not allowed | Error 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.
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 users | Service accounts | |
|---|---|---|
| Meant for | People, and tools outside the cluster | Pods and other workloads |
| Stored in Kubernetes | No. There is no User object | Yes, a namespaced ServiceAccount object |
| Created with | Something outside the cluster: a certificate, a company login, a token file | kubectl create serviceaccount |
| Proof | Client certificate or bearer token | A token signed by the cluster |
| Username | Whatever the proof says, for example alice | system: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.
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-adminorsystem: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
devorsystem: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
| Authenticator | Credential | Turned on by | Typical use |
|---|---|---|---|
| X.509 client certificates | A certificate signed by the cluster CA | --client-ca-file | Administrators and control plane components |
| Service account tokens | A signed JSON Web Token | --service-account-key-file, --service-account-issuer | Pods |
| Bootstrap tokens | A short token stored as a Secret in kube-system | --enable-bootstrap-token-auth | Nodes joining with kubeadm join |
| Static token file | A token listed in a CSV file | --token-auth-file | Learning and tests only |
| OpenID Connect (JWT) | An ID token from an identity provider | --authentication-config, or the older --oidc-* flags | Company logins on real clusters |
| Webhook | Any bearer token | --authentication-token-webhook-config-file | Asking an outside service to check tokens |
| Authenticating proxy | Headers set by a trusted proxy | --requestheader-* flags | The 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 filesuper-admin.confuses it; the normaladmin.confis in the groupkubeadm:cluster-admins, which gets its power from an ordinary ClusterRoleBinding.system:serviceaccountsandsystem:serviceaccounts:<namespace>: every service account, and every service account of one namespace.system:nodes: the kubelets, whose usernames aresystem: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 usersfails 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/manifestsand back. - Adding
--token-auth-filewithout mounting the file. The API server runs in a container. Without ahostPathvolume the path does not exist inside it, and the API server crash-loops. - Passing
--tokennext to a kubeconfig that holds a client certificate.kubectlsends both, and the certificate usually wins, so you test the wrong identity. Use a separate context, or--kubeconfig=/dev/nullas 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 (
CNis the user,Othe groups), service account tokens, bootstrap tokens, the static token file, OpenID Connect. The first to accept wins. - No credentials means
system:anonymous; bad credentials mean401; a valid identity without rights means403. kubectl auth whoamishows who you are, and--aslets 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.