Basic Auth configuration based on Traefik

This article was last updated on: February 7, 2024 pm

preface

Traefikis a modern HTTP reverse proxy and load balancer that makes it easy to deploy microservices.

Traefik can be integrated with multiple existing infrastructure components (Docker, Swarm pattern, Kubernetes, Marathon, Consul, Etcd, Rancher, Amazon ECS…). Integrate and configure yourself automatically and dynamically.

Series:

Today we are using Traefik on K8S to detail how to implement authentication capabilities with BasicAuth MiddleWare

Basic Auth 功能简图

The reason for using Basic Auth is simple, for example, we want to put an unauthenticated page on the public network, but for security reasons, we want only users with accounts and passwords to access it. For example, if you release the Prometheus UI/AlertManager UI to the public network, you can add Basic Auth.

Create BasicAuth MiddleWare

Create a YAML file: (As mentioned in the note, the users base64 string can be generated directly via htpasswd)

1
2
3
4
5
6
7
8
9
# 声明 `users` 所在的 secret
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
name: basic-auth
namespace: kube-system
spec:
basicAuth:
secret: authsecret

📝Notes:

Note: In Kubernetes secrets, strings (e.g. generated by htpasswd) must first be base64 encoded.
To create an encoded user:password pair, you can use the following command:
htpasswd -nb user password | openssl base64

1
2
3
4
5
6
7
8
9
apiVersion: v1
kind: Secret
metadata:
name: authsecret
namespace: kube-system
data:
users: |2
dGVzdDokYXByMSRINnVza2trVyRJZ1hMUDZld1RyU3VCa1RycUU4d2ovCnRlc3QyOiRhcHIxJGQ5
aHI5SEJCJDRIeHdnVWlyM0hQNEVzZ2dQL1FObzAK

Create an IngressRoute based on BasicAuth MiddleWare

As shown below, in middlewares Quoted in basic-auth:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: alertmanager
namespace: cert-manager
spec:
entryPoints:
- web
- websecure
routes:
- kind: Rule
match: Host(`alertmanager.e-whisper.com`)
middlewares:
- name: hsts-header
namespace: kube-system
- name: redirectshttps
namespace: kube-system
- name: basic-auth
namespace: kube-system
services:
- name: kube-prometheus-alertmanager
namespace: monitoring
port: 9093
tls: {}

verify

After visiting the corresponding page, a login dialog box will pop up, as follows:

Basic Auth 页面

Enter the account password correctly to access 🎉🎉🎉

📚️ Reference documentation

BasicAuth - Traefik

EOF


Basic Auth configuration based on Traefik
https://e-whisper.com/posts/19690/
Author
east4ming
Posted on
April 7, 2022
Licensed under