Understanding the Kubernetes 401 Unauthorized error (cert common name was my error)

I created a new k8s user, added a role and a role binding granting it access to list nodes, but when I tried running kubectl --context=bob-context get nodes I received the lovely error error: You must be logged in to the server (Unauthorized). If you search google, you get a lot of results saying “this is probably certificate expiration” and not too much else. My certificates were not expired.

I re-ran the command with higher verbosity and got

I0509 18:48:16.413290 6230 request.go:1181] Response Body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Unauthorized","reason":"Unauthorized","code":401}
I0509 18:48:16.413417 6230 helpers.go:219] server response object: [{
"kind": "Status",
"apiVersion": "v1",
"metadata": {},
"status": "Failure",
"message": "Unauthorized",
"reason": "Unauthorized",
"code": 401
}]
F0509 18:48:16.413430 6230 helpers.go:118] error: You must be logged in to the server (Unauthorized)

This was useful: the ‘Unauthorized’ bit is just telling me that we received a 401 back, not that I’m actually unauthorized. I may be unauthenticated.

I found my answer in the docs that deal with authorization – https://kubernetes.io/docs/reference/access-authn-authz/authentication/

Reading this, I immediately noticed this paragraph

Even though a normal user cannot be added via an API call, any user that presents a valid certificate signed by the cluster’s certificate authority (CA) is considered authenticated. In this configuration, Kubernetes determines the username from the common name field in the ‘subject’ of the cert (e.g., “/CN=bob”).

https://kubernetes.io/docs/reference/access-authn-authz/authentication/

I had been lazy when generating my cert and hadn’t specified a -subj field to openssl, so it had generated a default that didn’t match my user’s account name. Once I added that, I got past the error.

Advertisement

Author: jamandbees

There's just this whole, like, wha? Out there in the world, y'know? The jam and the bees, please.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: