Appearance
Kubernetes ServiceAccounts: Pod Authentication
What is a ServiceAccount?
An explanation of Kubernetes ServiceAccounts and the authentication mechanism for Pods.
What is a ServiceAccount?
A ServiceAccount is a specific type of non-human account in Kubernetes that provides a distinct identity for processes running within Pods.
- Purpose: Unlike User accounts (which are for humans and are often managed globally), ServiceAccounts are namespaced and intended for workloads (Pods) and system components to authenticate to the API server.
- Creation: Every namespace has a
defaultServiceAccount created automatically. You can also create custom ServiceAccounts for specific applications to enforce the principle of least privilege. - Binding: When you define a Pod, you can assign it a specific ServiceAccount using the
spec.serviceAccountNamefield. If you do not specify one, the Pod is automatically assigned thedefaultServiceAccount for its namespace.
How Pods Authenticate with the API Server
When a Pod needs to communicate with the Kubernetes API server (e.g., to read a ConfigMap or list other Pods), it uses a token associated with its ServiceAccount. The authentication flow works as follows:
Token Mount (Projected Volume): When a Pod is created, the Kubernetes control plane (specifically the ServiceAccount admission controller) modifies the Pod to include a Projected Volume. This volume contains a JSON Web Token (JWT) that proves the identity of the ServiceAccount.
- The kubelet fetches this time-bound token from the API server using the TokenRequest API.
- The token is mounted into the container at a standard path, typically
/var/run/secrets/kubernetes.io/serviceaccount/token.
Authentication Request: When an application inside the Pod calls the Kubernetes API, it reads this token from the file system and sends it in the HTTP header of the request:
Authorization: Bearer <token>.Validation: The API server validates the JWT signature, checks if it has expired, and verifies that the ServiceAccount and the Pod still exist. If valid, the API server treats the request as coming from that ServiceAccount (e.g.,
system:serviceaccount:my-namespace:my-service-account).Authorization: Once authenticated, the API server checks if that ServiceAccount has permission to perform the requested action (Authorization) via RBAC rules (RoleBindings or ClusterRoleBindings) linked to that account.
Key Behaviors
- Token Rotation: The kubelet automatically refreshes the token before it expires. The application inside the container is responsible for reloading the token from the disk if it changes, though many client libraries handle this automatically.
- Cleanup: When a Pod is deleted, its bound tokens are automatically invalidated.
- Opt-Out: You can disable this automatic mounting of credentials by setting
automountServiceAccountToken: falseon either the ServiceAccount or the Pod specification.