Kubernetes basic authentication with Traefik

5/2/2018

I am trying to configure Basic Authentication on a Nginx example with Traefik as Ingress controller.

I just create the secret "mypasswd" on the Kubernetes secrets.

This is the Ingress I am using:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: nginxingress
  annotations:
    ingress.kubernetes.io/auth-type: basic
    ingress.kubernetes.io/auth-realm: traefik
    ingress.kubernetes.io/auth-secret: mypasswd
spec:
  rules:
  - host: nginx.mycompany.com
    http:
      paths:
      - path: /
        backend:
          serviceName: nginxservice
          servicePort: 80

I check in the Traefik dashboard and it appear, if I access to nginx.mycompany.com I can check the Nginx webpage, but without the basic authentication.

This is my nginx deployment:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.7.9
        ports:
        - containerPort: 80

Nginx service:

apiVersion: v1
kind: Service
metadata:
  labels:
    name: nginxservice
  name: nginxservice
spec:
  ports:
    # The port that this service should serve on.
    - port: 80
  # Label keys and values that must match in order to receive traffic for this service.
  selector:
    app: nginx
  type: ClusterIP
-- Asier Gomez
kubernetes
kubernetes-ingress
traefik

1 Answer

5/2/2018

It is popular to use basic authentication. In reference to Kubernetes documentation, you should be able to protect access to Traefik using the following steps :

  1. Create authentication file using htpasswd tool. You'll be asked for a password for the user:

htpasswd -c ./auth

  1. Now use kubectl to create a secret in the monitoring namespace using the file created by htpasswd.

kubectl create secret generic mysecret --from-file auth --namespace=monitoring

  1. Enable basic authentication by attaching annotations to Ingress object:

ingress.kubernetes.io/auth-type: "basic"

ingress.kubernetes.io/auth-secret: "mysecret"

So, full example config of basic authentication can looks like:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: prometheus-dashboard
  namespace: monitoring
  annotations:
    kubernetes.io/ingress.class: traefik
    ingress.kubernetes.io/auth-type: "basic"
    ingress.kubernetes.io/auth-secret: "mysecret"
spec:
  rules:
  - host: dashboard.prometheus.example.com
    http:
      paths:
      - backend:
          serviceName: prometheus
          servicePort: 9090
  1. You can apply the example as following:

kubectl create -f prometheus-ingress.yaml -n monitoring

This should work without any issues.

-- d0bry
Source: StackOverflow