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=auth
secret "basic-auth" created


kubectl get secret basic-auth -o yaml
apiVersion: v1
data:
  auth: Zm9vOiRhcHIxJE9DRzZYeWJcJGNrKDBGSERBa29YWUlsSDkuY3lzVDAK
kind: Secret
metadata:
  name: basic-auth
  namespace: default
type: Opaque

3. 创建Ingress


---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  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/targets
HTTP/1.1 401 Unauthorized
Server: nginx/1.13.7
Date: Sat, 13 Jan 2018 16:03:41 GMT
Content-Type: text/html
Content-Length: 195
WWW-Authenticate: Basic realm="Authentication Required - user1"
Connection: keep-alive
Keep-Alive: timeout=15

➜ curl -I -XGET http://prom.k8s.mechat.im/targets -u "user1:bar"
HTTP/1.1 200 OK
Server: nginx/1.13.7
Date: Sat, 13 Jan 2018 16:06:05 GMT
Content-Type: text/html; charset=utf-8
Vary: Accept-Encoding
Transfer-Encoding: chunked
Connection: keep-alive
Keep-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
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Logo

开源、云原生的融合云平台

更多推荐