How to set secodary key for kubernetes ingress basic-auth

8/14/2019

I wanna have an ingress for all my service in the k8s, and give the ingress a basic auth. But for auth rotation, I want to support a secondary auth for user so the endpoint can be reached when they re-generate the primary key.

I currently can follow this guide to set up an ingress with single basic auth.

-- Yuwei Zhou
kubernetes
kubernetes-ingress
nginx-ingress

1 Answer

8/14/2019

Adapting the guide, you can put multiple usernames and passwords in the auth file you're using to generate the basic auth secret. Specifically, if you run the htpasswd command without the -c flag, so e.g. htpasswd <filename> <username> it will add an entry to the file rather than creating a new file from scratch:

$ htpasswd -c auth foo
New password: <bar>
Re-type new password: <bar>
Adding password for user foo

$ cat auth
foo:$apr1$isCec65Z$JNaQ0GJCpPeG8mR1gYsgM1

$ htpasswd auth user2
New password: <pass2>
Re-type new password: <pass2>
Adding password for user user2

$ cat auth
foo:$apr1$isCec65Z$JNaQ0GJCpPeG8mR1gYsgM1
user2:$apr1$.FsOzlqA$eFxym7flDnoDtymRLraA2/

If you've already created the secret in the first place via the given command:

$ kubectl create secret generic basic-auth --from-file=auth

You can then update the secret with this trick:

$ kubectl create secret generic basic-auth --from-file=auth\
  --dry-run -o yaml | kubectl apply -f -
Warning: kubectl apply should be used on resource created by either kubectl create --save-config or kubectl apply
secret/basic-auth configured

You can confirm setting the secret worked:

$ kubectl get secret basic-auth -ojsonpath={.data.auth} | base64 -D
foo:$apr1$isCec65Z$JNaQ0GJCpPeG8mR1gYsgM1
user2:$apr1$.FsOzlqA$eFxym7flDnoDtymRLraA2/

Finally, you can test basic auth with both usernames and passwords is working:

$ curl http://<minikube_ip>/ -H 'Host: foo.bar.com' \
  -s -w"%{http_code}" -o /dev/null
401

$ curl http://<minikube_ip>/ -H 'Host: foo.bar.com' \
  -u 'wronguser:wrongpass' \
  -s -w"%{http_code}" -o /dev/null
401

$ curl http://<minikube_ip>/ -H 'Host: foo.bar.com' \
  -u 'foo:bar' \
  -s -w"%{http_code}" -o /dev/null
200

$ curl http://<minikube_ip>/ -H 'Host: foo.bar.com' \
  -u 'user2:pass2' \
  -s -w"%{http_code}" -o /dev/null
200
-- Amit Kumar Gupta
Source: StackOverflow