Kubernetes Authentication vs Authorization
Kubernetes Authentication vs Authorization
Kubernetes Authentication vs Authorization
bitcodematrix.com | Kubernetes Series
1. Introduction
Two words appear in almost every Kubernetes security conversation and are confused just as often: authentication and authorization. They sound alike, they are often abbreviated the same way (authn and authz are sometimes both shortened to "auth"), and error messages do not always make clear which one has failed. Yet they are different steps with different questions, different configuration and different fixes. If you get a "401" and look for a missing Role, or get a "403" and regenerate your credentials, you will lose hours.
This article separates the two clearly. You will learn what each stage does in the Kubernetes API server, which authentication methods exist and when to use each, how authorization modes work and combine, how admission control fits in, and how to read the errors that each stage produces. It ties together the earlier articles in this series on RBAC, ServiceAccounts and the control plane, and ends with design guidance, a hands-on exercise and a troubleshooting guide.
2. The Core Difference
A familiar analogy is airport security. At the passport desk, an officer checks who you are by examining your identity document. That is authentication. Later, at the gate, an agent checks whether your ticket allows you to board this particular flight. That is authorization. Being a real person with a valid passport does not mean you may board every plane, and having a ticket is worthless if nobody can establish who you are.
Note that Kubernetes does not store human users. It has no User object and no password database. Authentication always relies on something outside the API, such as a certificate authority, an identity provider or the token signing key that Kubernetes uses for ServiceAccounts. Authorization, by contrast, is fully inside Kubernetes when you use RBAC.
3. The Life of an API Request
Every request to the API server, whether it comes from kubectl, a controller, a kubelet or a Pod, passes through a pipeline of stages. The diagram shows the order and what each stage rejects:
Figure 1: The stages of an API request and the errors they produce.
The order is strict. A request that fails authentication never reaches authorization, and one that fails authorization never reaches admission. Each stage sees only what the previous stage allowed through, which is a useful debugging aid: the error code tells you how far the request got.
4. Authentication in Kubernetes
4.1 How the Authenticator Chain Works
The API server can have several authentication methods enabled at the same time. It tries them in turn, and the first one that recognises and accepts the credentials determines the identity. The result is a small record:
Username, a string such as alice@example.com or system:serviceaccount:shop:app-sa.
UID, an optional identifier that is stable even if the name changes.
Groups, a list such as team-shop-devs and system:authenticated.
Extra, optional key-value data that webhooks and policies can use.
This record, and nothing else, is passed to authorization. Authorization never sees your password, your certificate or your token, only the identity that authentication derived from them.
4.2 Authentication Methods
4.3 Client Certificates
The identity is embedded in the certificate: the common name (CN) is the username and each organisation (O) is a group. A certificate with CN alice and O team-shop-devs authenticates as user alice in group team-shop-devs. Users can obtain such certificates through the CertificateSigningRequest API: they generate a key and a request, an administrator approves it, and the cluster signs it.
apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
name: alice
spec:
request: <base64-encoded PKCS#10 request>
signerName: kubernetes.io/kube-apiserver-client
expirationSeconds: 86400
usages:
- client auth
kubectl certificate approve alice
kubectl get csr alice -o jsonpath='{.status.certificate}' | base64 -d > alice.crt
Certificates work well for components, but they are awkward for people. Kubernetes does not support certificate revocation: a certificate is valid until it expires, even if the person leaves the company. The only remedies are short lifetimes or rotating the CA, which is disruptive. For human access, prefer OIDC.
4.4 OpenID Connect for People
OIDC lets you reuse your organisation's identity provider, with single sign-on, multi-factor authentication and central offboarding. The flow is:
The user signs in to the identity provider, usually in a browser, through a kubectl plugin that implements the login flow.
The identity provider returns a signed ID token that contains claims such as the email address and group memberships.
kubectl sends the ID token as a bearer token with each request.
The API server validates the token: signature (using the provider's published keys), issuer, audience (the client ID) and expiry. It then maps one claim to the username and another to the groups.
The API server is told about the provider with settings for the issuer URL, the client ID, and the names of the username and group claims, either through command-line flags or, in newer versions, through a structured authentication configuration file. Because the token is short-lived, kubectl refreshes it through the plugin. Offboarding is immediate in principle: when the identity provider disables the account, new tokens stop being issued and old ones expire shortly.
The group claim is the link to authorization. If the token does not contain the groups that your RoleBindings expect, the user will authenticate successfully and then be forbidden, which is a very common support issue.
4.5 ServiceAccount Tokens
Workloads authenticate with tokens that the API server itself issues and signs. These bound tokens are short-lived, audience-limited and tied to a Pod, and the identity they carry is system:serviceaccount:<namespace>:<name>. The ServiceAccount article in this series explains them in detail. The relevant point here is that a ServiceAccount token proves identity only; it carries no permissions until RBAC grants some.
4.6 Webhook Token Authentication and Authenticating Proxy
With webhook token authentication, the API server posts a TokenReview object to an external HTTPS service, which replies whether the token is valid and which user and groups it represents. Many managed Kubernetes services use this approach to accept their own cloud identities. With an authenticating proxy, a trusted component in front of the API server authenticates users in its own way and forwards the identity in headers. The API server trusts those headers only from clients that present a certificate signed by a configured CA, which is essential, because anyone able to set those headers directly could impersonate anybody.
4.7 Anonymous Requests
By default, the API server accepts requests without credentials and gives them the username system:anonymous and the group system:unauthenticated. This does not mean they can do anything. They still go through authorization, and default RBAC rules allow them only a few harmless endpoints, such as health checks and the version. Many hardened clusters disable anonymous authentication entirely. Be careful that nobody binds a useful role to system:anonymous or system:unauthenticated, because that would give it to the whole internet if the API server is reachable.
4.8 kubeconfig and Credential Plugins
A kubeconfig file ties together a cluster (address and CA), a user (credentials) and a context (which user for which cluster). A user entry can hold a certificate, a token or an exec credential plugin, which is a command that returns a fresh short-lived token on demand. Plugins are how OIDC logins and cloud identity tokens reach kubectl. Treat kubeconfig files as secrets: they can contain keys or tokens, so protect their file permissions, never commit them to Git and avoid sharing one file between people, because that destroys the audit trail.
4.9 Managed Kubernetes Services
On managed services, authentication is usually handled by the provider's own identity system: you sign in with your cloud account, the provider's plugin gets a token, and the API server accepts it through a webhook or an integrated mechanism. The provider then maps your cloud identity to a Kubernetes username and groups, through its own configuration, such as access entries or role mappings. Authorization is typically still RBAC, although some providers also offer cloud-native authorization. Learn the mapping on your platform, because it defines the groups that RBAC sees.
5. Authorization in Kubernetes
5.1 What the Authorizer Sees
Authorization works from the attributes of the request. These include the identity from authentication (user, groups, extra) and the details of the action:
5.2 Authorization Modes
The API server is started with one or more authorization modes, commonly Node and RBAC. Each authorizer answers with one of three results: allow, deny or no opinion. They are consulted in order, the first definite answer (allow or deny) wins, and if every authorizer has no opinion, the request is denied. This is the "default deny" rule.
Recent versions of Kubernetes also support a structured authorization configuration file, which allows an ordered chain of authorizers, including several webhooks, with more control over failure behaviour. Check the documentation for your version before relying on it.
5.3 RBAC in One Paragraph
RBAC is the mode you will use daily. A Role or ClusterRole lists allowed verbs on resources, and a RoleBinding or ClusterRoleBinding attaches it to users, groups or ServiceAccounts. Everything is additive, with no deny rules. The RBAC article in this series covers it in depth, including aggregation, default roles, escalation protection and dangerous permissions.
5.4 Impersonation
A user with the impersonate permission can send requests as another identity, with the --as and --as-group options of kubectl. The request is authenticated as the caller, authorized as the caller for the impersonation itself, and then authorized as the impersonated identity for the action. This is valuable for testing what a user or ServiceAccount can do, and for gateways that act on behalf of users. It is also powerful, so grant impersonation rarely. The audit log records both the real and the impersonated identity.
6. Admission: Neither Authentication Nor Authorization
The third stage is often mistaken for part of the security model of identity, but it answers a different question: not "who are you?" or "may you act?", but "is this particular object acceptable?". Admission controllers run after authorization. Mutating controllers can modify the object, for example by injecting defaults or sidecars. Validating controllers can reject it, for example because a Pod runs as root or lacks resource limits. Examples include Pod Security admission, resource quota checks, ValidatingAdmissionPolicy and custom admission webhooks.
The distinction matters for troubleshooting. A user may be perfectly authenticated and fully authorized to create Pods, and the request can still fail because a policy rejects the specific Pod. The error message for such a rejection names the admission plugin or policy, and the RBAC rules need no change.
7. Telling the Two Apart: 401, 403 and Other Errors
A quick rule of thumb: 401 means "I do not know who you are", and 403 means "I know who you are, and the answer is no."
8. Three Typical Flows
8.1 A Developer Using kubectl With Single Sign-On
The developer signs in at the identity provider, and the credential plugin obtains an ID token. kubectl sends it with each request. The API server validates the token (authentication) and derives alice@example.com with the group team-shop-devs. The RBAC authorizer finds a RoleBinding that grants that group the edit role in the namespace shop (authorization), and admission policies then check the objects that she creates.
8.2 A Pod Calling the API
A Pod that runs as ServiceAccount ci-deployer reads its projected token and sends it to the API server. Authentication validates the signature, expiry, audience and the binding to the Pod, and yields system:serviceaccount:shop:ci-deployer. RBAC then checks the Roles bound to that account.
8.3 A Kubelet Reporting Node Status
The kubelet presents a client certificate, so authentication yields a node identity in the group system:nodes. The Node authorizer allows it to read only objects related to Pods on its own node, and the NodeRestriction admission plugin prevents it from modifying objects that belong to other nodes. This is a good example of all three stages cooperating to limit the damage of a compromised node.
9. Designing Identity and Access
Several principles run through this table:
Centralise human identity. One identity provider, with multi-factor authentication and quick offboarding, beats scattered certificates and tokens.
Prefer short-lived credentials over long-lived ones everywhere, because Kubernetes cannot revoke certificates.
Authorize through groups, so that access follows team membership rather than individual accounts.
Separate identity from permission. Keep the authentication setup stable and manage permissions through reviewed RBAC manifests.
Never share identities. Shared kubeconfigs and shared accounts make audit logs useless.
Plan for failure of the identity provider. Keep a tested break-glass path, so that an outage of single sign-on does not lock you out of the cluster.
10. Hands-On Walkthrough
This exercise makes the difference between 401 and 403 visible. Use a test cluster. The -k flag skips certificate verification and is acceptable only in a lab.
Find out how the cluster sees you, and what you can do.
kubectl auth whoami
kubectl auth can-i list pods -n default
kubectl auth can-i --list -n default | head -20
The first command, available in recent kubectl versions, prints your username and groups as the API server derived them from your credentials. This is authentication information. The next two show authorization decisions.
Look at the API server address, and call it with no credentials.
APISERVER=$(kubectl config view --minify -o jsonpath='{.clusters[0].cluster.server}')
curl -sk $APISERVER/api/v1/namespaces
If anonymous access is enabled, the response is a 403 Forbidden message naming system:anonymous. The request was treated as an anonymous identity and then denied by authorization. If anonymous access is disabled, you get a 401 Unauthorized response instead.
Call it with a bogus token.
curl -sk -H "Authorization: Bearer not-a-real-token" \
$APISERVER/api/v1/namespaces
The answer is 401 Unauthorized. The credentials were supplied but not recognised, so the request never reached authorization.
Create a ServiceAccount with no permissions, and request a token for it.
kubectl create namespace authn-demo
kubectl create serviceaccount probe -n authn-demo
TOKEN=$(kubectl create token probe -n authn-demo)
curl -sk -H "Authorization: Bearer $TOKEN" \
$APISERVER/api/v1/namespaces/authn-demo/pods
This time you get a 403 Forbidden naming system:serviceaccount:authn-demo:probe. The token was valid, so authentication succeeded, but no rule allows listing Pods.
Grant the permission, and repeat.
kubectl create role pod-lister -n authn-demo --verb=list --resource=pods
kubectl create rolebinding probe-lists -n authn-demo \
--role=pod-lister --serviceaccount=authn-demo:probe
curl -sk -H "Authorization: Bearer $TOKEN" \
$APISERVER/api/v1/namespaces/authn-demo/pods
The call now succeeds with an empty list. Nothing about the credentials changed. Only the authorization decision did.
Clean up.
kubectl delete namespace authn-demo
11. Auditing Both Stages
The API server audit log is the place to see authentication and authorization results together. Each event records the authenticated user and groups, the impersonated user if any, the verb and object, the response code, and annotations that include the authorization decision and the reason. With audit logging, you can answer questions such as who changed this RoleBinding, which requests were denied for a user in the last hour, and which ServiceAccount read these Secrets.
Record Secret access at the Metadata level, so that the log shows who read them but not their content.
Alert on bursts of 401 responses, which can indicate stolen, expired or guessed credentials, and on unusual 403 responses for privileged identities.
Alert on use of break-glass identities and on changes to RBAC objects and to authentication configuration.
Send audit logs to a separate system that cluster administrators cannot easily alter.
12. Troubleshooting
13. Best Practices
Keep the two ideas apart in your head and in your runbooks: first prove who the caller is, then decide what the caller may do.
Use OIDC with single sign-on and multi-factor authentication for people, and avoid long-lived client certificates and static tokens for humans.
Use short-lived, bound credentials for workloads and pipelines, and avoid storing kubeconfigs with static credentials in CI systems.
Disable anonymous authentication where you can, and never bind roles to system:anonymous, system:unauthenticated or system:authenticated.
Authorize through groups with least-privilege RBAC, and review bindings regularly.
Protect the Node authorizer and NodeRestriction settings, and harden the kubelet by disabling anonymous access and using webhook authorization.
Layer admission policies on top of RBAC, because permission to create an object does not mean every object should be accepted.
Keep a documented, tested break-glass procedure that does not depend on your identity provider.
Enable audit logging, and monitor both authentication failures and authorization denials.
Learn how your managed Kubernetes provider maps cloud identities to Kubernetes users and groups, and document it.
14. Conclusion
Authentication and authorization are two gates in series. The first establishes an identity from credentials the API server can verify, and the second decides whether that identity may perform the specific action on the specific resource. They produce different errors, they are configured in different places and they are fixed in different ways. Admission control then sits behind both, enforcing policy on the objects themselves.
When you understand this pipeline, security design and troubleshooting both become systematic: choose strong, short-lived authentication methods suited to each kind of identity, express permissions through groups and least-privilege roles, add admission policies for what permissions alone cannot control, and read every error by asking which stage produced it. That discipline is what keeps a Kubernetes cluster both usable and safe.