kubernetes

Kubernetes Authentication vs Authorization

Kubernetes Authentication vs Authorization

By Shubhankar Tripathi • • 5 min read

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.

Aspect

Authentication (authn)

Authorization (authz)

Question

Who are you?

Are you allowed to do this?

Input

Credentials: certificate, token, headers

The identity, plus the request: verb, resource, namespace

Output

A username, groups and extra attributes, or a failure

Allow or deny

Failure response

HTTP 401 Unauthorized

HTTP 403 Forbidden

Configured with

API server authentication flags or configuration, identity providers, certificates

Authorization modes, RBAC objects, webhooks

Managed by in practice

Identity and security teams, cluster operators

Platform and security teams, using RBAC manifests

Typical fix for a failure

Renew or correct credentials, fix the identity provider setup

Add or correct a Role and binding

 

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:

A request passes authentication, authorization and admission before it is stored, with 401, 403 and policy rejections at each stage

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.

Stage

What happens

Transport

The client opens a TLS connection and verifies the API server's certificate against the cluster CA. A failure here is a TLS error, not an authn or authz error

Authentication

The API server tries its configured authenticators on the request. A success yields a username, a UID, groups and extra attributes. If none succeeds, the request is rejected with 401, or treated as anonymous if that is enabled

Authorization

The authorizers check whether that identity may perform the verb on the resource. If none allows it, the answer is 403

Admission

Mutating and validating admission controllers can change the object or reject it based on policy, regardless of who is asking

Validation and storage

The object is checked against its schema and written to etcd

 

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

Method

How it works

Typical use

X.509 client certificates

The client presents a certificate signed by a trusted CA. The common name becomes the username and the organisation fields become groups

Cluster components, bootstrap and break-glass access

OpenID Connect (OIDC) tokens

The client presents a signed ID token from an identity provider. The API server validates issuer, audience, signature and expiry, and reads username and groups from claims

Human users with single sign-on

ServiceAccount tokens

Signed JWT tokens issued by the API server for Pods; bound to the Pod and time-limited

Workloads inside the cluster

Webhook token authentication

The API server sends the bearer token to an external service, which answers with the identity

Integration with a custom or cloud identity system

Authenticating proxy

A trusted front proxy authenticates the user and passes the identity in request headers

Aggregated API servers and some custom gateways

Bootstrap tokens

Short-lived tokens that let new nodes join and request certificates

Node bootstrapping

Static token or password files

Tokens listed in a file on the API server

Avoid. They are long-lived, cannot be rotated without restarting, and are hard to manage

Anonymous

Requests with no valid credentials are given the identity system:anonymous

Only for health endpoints; see Section 4.7

 

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:

  1. The user signs in to the identity provider, usually in a browser, through a kubectl plugin that implements the login flow.

  2. The identity provider returns a signed ID token that contains claims such as the email address and group memberships.

  3. kubectl sends the ID token as a bearer token with each request.

  4. 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:

Attribute

Example

Verb

get, list, watch, create, update, patch, delete (derived from the HTTP method and the request shape)

API group

The core group (empty), apps, batch, rbac.authorization.k8s.io

Resource and subresource

pods, deployments, pods/log, pods/exec

Resource name

A specific object name, when the request names one

Namespace

shop, or none for cluster-scoped resources

Non-resource path

URLs such as /healthz or /metrics

 

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.

Mode

What it does

Notes

Node

Special-purpose authorizer for kubelets: a kubelet may read only the Secrets, ConfigMaps and volumes of Pods scheduled to its own node

Used with the NodeRestriction admission plugin, which also limits what a kubelet may modify

RBAC

Rules in Roles and ClusterRoles, attached to subjects by bindings, stored in the API

The standard mode for users and ServiceAccounts

Webhook

The API server asks an external service, through a SubjectAccessReview, whether to allow the request

Used for custom policy engines and some managed offerings

ABAC

Attribute-based rules from a policy file on the API server

Legacy. Needs an API server restart to change, so avoid it

AlwaysAllow and AlwaysDeny

Allow or deny everything

For testing only. AlwaysAllow in production disables authorization completely

 

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

What you see

What it means and where to look

error: You must be logged in to the server (Unauthorized), HTTP 401

Authentication failed. The credentials are missing, expired, malformed, signed by an unknown CA or issuer, or the token was revoked or bound to a deleted Pod. Fix credentials or identity provider settings. Changing RBAC will not help

Error from server (Forbidden): ... User "alice" cannot list resource "pods" in API group "" in the namespace "shop", HTTP 403

Authentication succeeded and the identity is known. Authorization denied the action. Read the user, verb, resource and namespace in the message and compare them with your Roles and bindings

User "system:anonymous" cannot ...

The request carried no valid credentials and was treated as anonymous, and then denied. Treat it as an authentication problem: why were the credentials not recognised?

Forbidden message that names a webhook or policy, for example admission webhook "x" denied the request

Admission rejected the object. Fix the object to comply with the policy, or review the policy

x509: certificate signed by unknown authority

A TLS problem. The client does not trust the API server's certificate. This is the client verifying the server, not the server authenticating the client

Unable to connect to the server: dial tcp ... timeout or refused

A network problem. The request never reached the API server, so neither stage was involved

Token expired, not yet valid, or invalid audience or issuer messages

Authentication of an OIDC or ServiceAccount token. Check clock synchronisation, the expiry, the audience and the issuer configuration

 

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

Identity type

Recommended authentication

Recommended authorization

Human users

OIDC with the organisation's identity provider, including multi-factor authentication

RBAC bindings to groups, with namespaced roles for most people

Administrators

OIDC, with a separate privileged group, possibly time-limited elevation

Narrow, purpose-built roles; cluster-admin only for few and for emergencies

Break-glass access

A protected certificate or credential, stored securely and used rarely

High privilege, audited and reviewed after use

Pods and controllers

Bound ServiceAccount tokens

A dedicated ServiceAccount and minimal Role per workload

CI/CD pipelines

Short-lived tokens through OIDC federation or workload identity, not stored kubeconfigs

A deployer Role limited to the target namespaces and resources

Cloud services calling the cluster

The cloud provider's identity integration

Mapped to specific groups with minimal roles

Kubelets and nodes

Client certificates through TLS bootstrapping, with rotation

Node authorizer and NodeRestriction

 

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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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.

  1. 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

Symptom

Likely cause and check

401 right after a long idle period

The token or certificate expired. Re-authenticate, and check that your credential plugin refreshes tokens

401 for a new cluster or context

The kubeconfig points at the wrong cluster or user, or the CA data does not match. Check kubectl config view --minify

401 with OIDC

Wrong issuer or audience in the API server configuration, clock skew between the API server and the provider, expired token, or a broken credential plugin. Decode the token claims and compare them with the settings

403 although login works

The authenticated username or groups differ from those in your bindings. Check kubectl auth whoami and compare names and case with your RoleBindings

403 only for group-based access

The identity provider does not include the groups in the token, or the claim name differs from the API server setting

403 for a ServiceAccount in a Pod

The Pod uses a different ServiceAccount than you think, or the binding names the wrong namespace. Check the Pod spec and the subject

403 for cluster-scoped resources

A namespaced RoleBinding cannot grant them. A ClusterRole with a ClusterRoleBinding is needed

Everything works as admin but not for a user

Authentication is not the problem. Compare permissions with kubectl auth can-i --list --as for the user

Rejected by a named admission webhook or policy

Not an identity issue. Read the policy message and adjust the object or the policy

Sudden 401s for many Pods after a change

ServiceAccount signing key or issuer configuration changed. Review recent control plane changes

Works from one machine, 401 from another

Different kubeconfig, expired local credentials or a missing plugin binary on the second machine

 

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.