traefik配置用户登录,限制K8S的web服务访问
背景
像Elastic-APM, Traefik-Dashboard等页面,是没有用户登录限制的,如果我们希望给他们加上用户登录限制,我们需要在traeifk里给对应的ingress添加登录用的Middleware,那么该如何添加呢?本文以给K8S部署的traefik dashboard为例进行添加
用户名密码加密
1.假设有如下3个用户名密码lizhenwei 123
zhenwei.li 456
hello thankyou
2.我们通过htpasswd进行加密
htpasswd -nb lizhenwei 123
lizhenwei:$apr1$0wIJg4EG$RZ7wOIyIdg1R4gj4zAlzq1
htpasswd -nb zhenwei.li 456
zhenwei.li:$apr1$PX8cqECj$5zvC3eB1vhLioyjVjdkkE/
htpasswd -nb hello thankyou
hello:$apr1$4nlPGEqZ$nqz2ojkuxAY4FUEy0Tp3x1
3.将加密的信息放入一个叫policy的文件
vi policy
lizhenwei:$apr1$0wIJg4EG$RZ7wOIyIdg1R4gj4zAlzq1 zhenwei.li:$apr1$PX8cqECj$5zvC3eB1vhLioyjVjdkkE/ hello:$apr1$4nlPGEqZ$nqz2ojkuxAY4FUEy0Tp3x1
4.进行base64加密,获得加密后的字符
cat policy | openssl base64
bGl6aGVud2VpOiRhcHIxJDB3SUpnNEVHJFJaN3dPSXlJZGcxUjRnajR6QWx6cTEK emhlbndlaS5saTokYXByMSRQWDhjcUVDaiQ1enZDM2VCMXZoTGlveWpWamRra0Uv CmhlbGxvOiRhcHIxJDRubFBHRXFaJG5xejJvamt1eEFZNEZVRXkwVHAzeDEK
创建middleware.yaml
将加密后的字符,复制到data.users下面
# Declaring the user list
apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
name: test-auth
spec:
basicAuth:
secret: authsecret
---
# Note: in a kubernetes secret the string (e.g. generated by htpasswd) must be base64-encoded first.
# To create an encoded user:password pair, the following command can be used:
# htpasswd -nb user password | openssl base64
apiVersion: v1
kind: Secret
metadata:
name: authsecret
namespace: default
data:
users: |2
bGl6aGVud2VpOiRhcHIxJDB3SUpnNEVHJFJaN3dPSXlJZGcxUjRnajR6QWx6cTEK
emhlbndlaS5saTokYXByMSRQWDhjcUVDaiQ1enZDM2VCMXZoTGlveWpWamRra0Uv
CmhlbGxvOiRhcHIxJDRubFBHRXFaJG5xejJvamt1eEFZNEZVRXkwVHAzeDEK
创建ingress.yaml
定义访问路径,定义中间件
# dashboard.yaml
apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
name: dashboard
spec:
entryPoints:
- web
routes:
- match: Host(`traefik.test.local`) && (PathPrefix(`/dashboard`) || PathPrefix(`/api`))
kind: Rule
services:
- name: api@internal
kind: TraefikService
middlewares:
- name: test-auth
生效配置
kubectl apply -f middleware.yaml
kubectl apply -f ingress.yaml
检查打开网页时,是否弹出登录对话框
更新密码
如果我们要更新密码,可以重新使用htpasswd生成密码,然后放在policy文件中,使用命令行更新
kubectl create secret generic authsecret --from-file=users=./policy --dry-run=client -o yaml | kubectl apply -f -