kubernetes - add basic auth authentication for Ingress


  • Kubernetes1.8.5
  • Ingress Controller: 0.9.0

Note: only versions above 0.9.0-beta.12 are supported

1. Create user password

First of all, we need to install the htpasswd binary file to generate an "auth" file through htpasswd; it is used to access the user we created and the encrypted password.

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

htpasswd auth user2
2nd user:
htpasswd auth user2
New password: <bar>
New password:
Re-type new password:
Adding password for user user2

2. Create kubernetes secret to store user/pass pairs

kubectl -n <namespace> create secret generic basic-auth --from-file=auth
secret "basic-auth" created

kubectl get secret basic-auth -o yaml
apiVersion: v1
kind: Secret
  name: basic-auth
  namespace: default
type: Opaque

3. Create Ingress

apiVersion: extensions/v1beta1
kind: Ingress
  name: prometheus
  namespace: monitoring
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: basic-auth
    nginx.ingress.kubernetes.io/auth-realm: "Authentication Required - user1"
    - host: prom.xxxxx.im
          - path: /
              serviceName: prometheus-svc
              servicePort: 9090


➜  curl -I http://prom.xxxx.im/targets
HTTP/1.1 401 Unauthorized
Server: nginx/1.13.7
Date: Sat, 13 Jan 2018 16:03:41 GMT
Content-Type: text/html
Content-Length: 195
WWW-Authenticate: Basic realm="Authentication Required - user1"
Connection: keep-alive
Keep-Alive: timeout=15

➜ curl -I -XGET http://prom.k8s.mechat.im/targets -u "user1:bar"
HTTP/1.1 200 OK
Server: nginx/1.13.7
Date: Sat, 13 Jan 2018 16:06:05 GMT
Content-Type: text/html; charset=utf-8
Vary: Accept-Encoding
Transfer-Encoding: chunked
Connection: keep-alive
Keep-Alive: timeout=15

Now it is successful to add the basic-auth authentication function. It is recommended to create the base-auth secret together with the initialization when creating the namespace.

Reference address: https://github.com/kubernetes/ingress-nginx/blob/master/docs/user-guide/annotations.md#authentication

By Yichen Wong
Link: https://www.jianshu.com/p/4d5aa1995de3
Source: Jianshu
The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

Tags: Nginx Kubernetes curl encoding

Posted on Sat, 04 Apr 2020 22:16:00 -0700 by sgt.wolfgang