Authentication & Authorization in Kubernetes

🔐 Part 1: User Authentication
Below is the process to create a Kubernetes user who can authenticate and access the cluster using a TLS certificate.
All steps are for creating a certificate-based user.
Generate a private RSA key named krishna.key:
openssl genrsa -out krishna.key 2048
Generate a Certificate Signing Request (CSR) using a private key:
openssl req -new -key krishna.key -out krishna.csr -subj "/CN=krishna"
Encode the CSR file in base64 format:
cat krishna.csr | base64 | tr -d '\n' > krishna.csr.base64
Now create the CSR YAML:
vim csr.yaml
Replace <BASE64_ENCODED_CSR> with the output of cat krishna.csr.base64
This YAML defines a Kubernetes CertificateSigningRequest (CSR) resource that you can apply with kubectl to request a certificate from the Kubernetes API server.
kubectl apply -f csr.yaml
kubectl get csr
Approve the CSR:
kubectl certificate approve krishna
Export the issued certificate from the CertificateSigningRequest to a yaml:
kubectl get csr krishna -o yaml > krishna-cert.yaml
Decode and save the certificate:
kubectl get csr krishna -o jsonpath='{.status.certificate}' | base64 -d > krishna.crt
✅ You now have:
krishna.key: private key
krishna.csr: CSR file
krishna.csr.base64: CSR file in base64 format
csr.yaml: YAML to definr CSR resource
krishna-cert.yaml: YAML of approved CSR with certificate
krishna.crt: signed certificate
🛠️ Part 2: User Authorization
Step 1: Create a Role or ClusterRole
vim role.yaml
kubectl apply -f role.yaml
Step 2: Bind the Role to your user (krishna)
vim role-binding.yaml
kubectl apply -f role-binding.yaml
k auth can-i get pod --as krishna
k auth can-i watch pod --as krishna
k auth can-i list pod --as krishna
k auth can-i delete pod --as krishna
🧪 Step 3: Configure a kubeconfig file for user krishna
Configure kubectl with a new user credential named krishna, which uses a TLS certificate and private key for authentication:
Get cluster name:
Use below command to create a named context in your kubeconfig file so that kubectl knows which cluster and which user to use together:
Then test:
kubectl auth can-i list pods
To access Kubernetes resources using a REST API via curl:
kubectl cluster-info
Subscribe to my newsletter
Read articles from Sanket Nankar directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
