Add basic authentication to Kubernetes Ingress nginx

0
40
Add basic authentication to Kubernetes Ingress nginx
Add basic authentication to Kubernetes Ingress nginx

Wonder how to add basic authentication to Ingress? I am going to show you how to add basic authentication to Kubernetes Ingress nginx in this post.

Step 1: Generate user and password

First thing to do is to generate user and password for the basic authentication, we will use the htpasswd. Let say we want to generate user admin and password verysecret, we will issue this command:

$ htpasswd -nb 'admin' 'verysecret' | base64
YWRtaW46JGFwcjEkUVU1cTdUMFAkRVk3M1QxNE1tdEZwdDEyU2d6VE9ILgoK

Step 2: Create the secret

Copy the generated password from previous step and use this in following secret template:

# mysecret.yaml
apiVersion: v1
kind: Secret
type: Opaque
metadata:
  name: basic-auth
data:
  auth: "YWRtaW46JGFwcjEkUVU1cTdUMFAkRVk3M1QxNE1tdEZwdDEyU2d6VE9ILgoK"

Apply the template:

$ kubectl apply -f mysecret.yaml

Step 3: Update Ingress

To add basic authentication to the Ingress controller, we only need to update these two annotation:

metadata:
  annotations:
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: basic-auth
  • auth-type: to determine the type of authentication, in this case, it is basic.
  • auth-secret: to specify the name of the secret that contains the authentication credentials. In this case, we created in previous step, its name is basic-auth.

This is a sample Ingress template:

# ingress.yaml
kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: blog.petehouston.com
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: "letsencrypt-production"
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: basic-auth
    nginx.ingress.kubernetes.io/auth-realm: "Authentication Required"
spec:
  tls:
  - hosts:
    - blog.petehouston.com
    secretName: tls-blog
  rules:
  - host: blog.petehouston.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: nginx
            port:
              number: 80

Apply the Ingress and test your site on the browser.

Conclusion

That’s it, I’ve shown you how to add basic authentication to Kubernetes Ingress nginx.

For more information, please take a look at Ingress controller basic authentication documentation.

Have fun!