Kubernetes: User Authorization with Certificate

Generate a private key:

openssl genrsa -out newuser.key 2048

Generate a certificate signing request (csr) from private key:

CN is the user, O is the group.

openssl req -new -key newuser.key -out newuser.csr -subj "/CN=user/O=dev/O=ops"

We create CertificateSigningRequest to Kubernetes:

.spec.signerName read here.

apiVersion: certificates.k8s.io/v1
kind: CertificateSigningRequest
metadata:
  name: newuser
spec:
  request: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURSBSRVFVRVN...
  signerName: kubernetes.io/kube-apiserver-client
  usages:
    - client auth
  # Below this is not required
  expirationSeconds: 864000 # one day, default is one year  
  groups:
    - system:authenticated

Once you send the CSR, you can query it with:

kubectl get csr

Now Admin will approve/deny the CSR:

kubectl certificate approve newuser
kubectl certificate deny newuser

Once you got approved, fetch the signed certificate and wrap in base64:

kubectl get csr/newuser -o jsonpath='{.status.certificate}' | base64 -d > newuser.crt

Using HTTP request:

curl https://<kubernetes-ip>:<kubernetes-port>/api --cert newuser.crt --key newuser.key --insecure

Using Kubeconfig:

kubectl config set-credentials newuser --client-key=newuser.key --client-certificate=newuser.crt --embed-certs=true

Set a new context:

kubectl config set-context newuser --current --user=newuser

Switch to new context:

kubectl config use-context newuser

At this point you should be able to access resources allowed by Role and RoleBinding for this user.

References: