Middleware helps to tweak the requests before reaching the actual service in kubernetes. Traefik support multiple middleware and one can use them depending on their needs. Some of the middleware helps with basic authentication, and some of the middleware helps with redirection. Middleware also helps to modify the request headers for incoming requests. The following image is from traefik documentation which explains how the traffic flow happens and the role of middlewares. Traefik-supported middleware is categorized into two categories. 1. HTTP 2. TCP. This article will demonstrate Trafik’s BasicAuth middleware.
Traefik Middleware – BasicAuth:
Let’s try the traefik BasicAuth middleware. It restricts access to your services to known users by enabling authentication.
1. Create the encrypted secret which consists username and password. My username is “lingesh” and my password is “test@123”
root@kmaster1:~# htpasswd -nb lingesh test@123 | base64 bGluZ2VzaDokYXByMSR6TFR5MEZRaiR4VXMyOFVSMWE4eDNER0xCZXA4amwxCgo= root@kmaster1:~#
2. Create a secret manifest like below. Create the secret.
apiVersion: v1 kind: Secret metadata: name: authsecret data: users: | bGluZ2VzaDokYXByMSR6TFR5MEZRaiR4VXMyOFVSMWE4eDNER0xCZXA4amwxCgo=
root@kmaster1:~# kubectl create -f secret_basic_auth.yaml secret/basicauth created root@kmaster1:~# kubectl get secret basicauth NAME TYPE DATA AGE basicauth Opaque 1 10s root@kmaster1:~#
3. Create a “BasicAuth” middleware manifest like below and create the resource.
root@kmaster1:~# cat Middleware_basic_auth.yaml apiVersion: traefik.containo.us/v1alpha1 kind: Middleware metadata: name: nginx-basicauth spec: basicAuth: secret: authsecret root@kmaster1:~#
root@kmaster1:~# kubectl create -f Middleware_basic_auth.yaml middleware.traefik.containo.us/nginx-basicauth created root@kmaster1:~# root@kmaster1:~# kubectl get middlewares NAME AGE nginx-basicauth 118s root@kmaster1:~#
4. Create a new ingressroute manifest by associating the middleware that has been created in the above step.
apiVersion: traefik.containo.us/v1alpha1 kind: IngressRoute metadata: name: nginx namespace: default spec: entryPoints: - web routes: - match: Host(`nginx.ua.com`) kind: Rule middlewares: - name: nginx-basicauth services: - name: nginx-deployment port: 80
Create the ingressroute.
root@kmaster1:~# kubectl create -f ingress_basic_auth.yaml ingressroute.traefik.containo.us/nginx created root@kmaster1:~# kubectl get ingressroute NAME AGE nginx 6s root@kmaster1:~#
Test our work:
1. Try to access the URL “nginx.ua.com”. It should prompt you to enter a username and password.
2. Enter the secrets which you have created in step#1 in the previous section to authenticate. You should be able to see the nginx welcome page.
3. You can check the middleware details in the traefik dashboard as well.
We have successfully enabled BasicAuth middleware in the traefik ingress for the nginx deployment. Hope this article is informative to you.
Leave a Reply