kubernetes - 为Ingress添加basic-auth认证

时间:2022-03-05 07:55:25

Requirement

  • Kubernetes1.8.5
  • Ingress Controller: 0.9.0

注意: 只有0.9.0-beta.12以上版本才支持

1.创建用户密码

首先需要安装htpasswd二进制文件,通过htpasswd生成一个“auth”文件;用来存取我们创建的用户及加密之后的密码。

htpasswd -c auth user1
New password: <bar>
New password:
Re-type new password:
Adding password for user user1

htpasswd auth user2
2nd user:
htpasswd auth user2
New password: <bar>
New password:
Re-type new password:
Adding password for user user2

2. 创建kubernetes secret来存储user/pass pairs

kubectl -n <namespace> create secret generic basic-auth --from-file=authsecret "basic-auth" createdkubectl get secret basic-auth -o yamlapiVersion: v1data:  auth: Zm9vOiRhcHIxJE9DRzZYeWJcJGNrKDBGSERBa29YWUlsSDkuY3lzVDAKkind: Secretmetadata:  name: basic-auth  namespace: defaulttype: Opaque

3. 创建Ingress

---apiVersion: extensions/v1beta1kind: Ingressmetadata: name: prometheus namespace: monitoring annotations:    nginx.ingress.kubernetes.io/auth-type: basic    nginx.ingress.kubernetes.io/auth-secret: basic-auth    nginx.ingress.kubernetes.io/auth-realm: "Authentication Required - user1"spec: rules: - host: prom.xxxxx.im http: paths: - path: / backend: serviceName: prometheus-svc servicePort: 9090

验证

➜  curl -I http://prom.xxxx.im/targetsHTTP/1.1 401 UnauthorizedServer: nginx/1.13.7Date: Sat, 13 Jan 2018 16:03:41 GMTContent-Type: text/htmlContent-Length: 195WWW-Authenticate: Basic realm="Authentication Required - user1"Connection: keep-aliveKeep-Alive: timeout=15➜ curl -I -XGET http://prom.k8s.mechat.im/targets -u "user1:bar"HTTP/1.1 200 OKServer: nginx/1.13.7Date: Sat, 13 Jan 2018 16:06:05 GMTContent-Type: text/html; charset=utf-8Vary: Accept-EncodingTransfer-Encoding: chunkedConnection: keep-aliveKeep-Alive: timeout=15

现在就添加basic-auth认证功能成功了,建议将base-auth secret在同创建namespace时初始化一起创建。

参考地址: https://github.com/kubernetes/ingress-nginx/blob/master/docs/user-guide/annotations.md#authentication



作者:YichenWong
链接:https://www.jianshu.com/p/4d5aa1995de3
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。