Please enable Javascript to view the contents

如何给 Kubernetes 服务添加 Basic 认证访问

 ·  ☕ 1 分钟

1. 部署 Ingress Controller

  • 查看 Kubernetes 版本
1
2
3
4
kubectl version --short

Client Version: v1.21.4
Server Version: v1.21.4
  • 查找兼容的 Nginx Ingress 版本
Helm Chart versionHelm Chart 最高可用版本K8s 适配版本
3.x.x3.36.01.16+
4.x.x4.4.21.19+

参考: https://github.com/kubernetes/ingress-nginx

  • 安装 Nginx Ingress Controller
1
2
3
helm upgrade --install ingress-nginx ingress-nginx \
  --repo https://kubernetes.github.io/ingress-nginx \
  --namespace ingress-nginx --create-namespace --version v4.4.2
  • 查看服务
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
kubectl -n ingress-nginx get svc

NAME                                 TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)                      AGE
ingress-nginx-controller             LoadBalancer   10.233.11.232   <pending>     80:30914/TCP,443:31493/TCP   14m
ingress-nginx-controller-admission   ClusterIP      10.233.56.67    <none>        443/TCP                      14m
kae@node1:~$ kubectl -n ingress-nginx get pod,svc
NAME                                            READY   STATUS    RESTARTS   AGE
pod/ingress-nginx-controller-666f45c794-h2zk9   1/1     Running   0          14m

NAME                                         TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)                      AGE
service/ingress-nginx-controller             LoadBalancer   10.233.11.232   <pending>     80:30914/TCP,443:31493/TCP   14m
service/ingress-nginx-controller-admission   ClusterIP      10.233.56.67    <none>        443/TCP                      14m

2. 添加秘钥

  • 生成秘钥
1
2
3
htpasswd -nb 'admin' 'xxxxxx' | base64

xxxxxxxxxxxxxxxxxxxxxx

登录用户 admin,登录密码 xxxxxx

  • 在服务所在命名空间,添加凭证
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Secret
type: Opaque
metadata:
  namespace: longhorn-system
  name: basic-auth
data:
  auth: "xxxxxxxxxxxxxxxxxxxxxx"
EOF

3. 添加 Ingress 转发规则

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cat <<EOF | kubectl apply -f -
kind: Ingress
apiVersion: networking.k8s.io/v1
metadata:
  name: longhorn-ingress
  namespace: longhorn-system
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/auth-secret: basic-auth
    nginx.ingress.kubernetes.io/auth-realm: "Authentication Required"
spec:
  rules:
  - host: longhorn.chenshaowen.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: longhorn-frontend
            port:
              number: 80
EOF

nginx.ingress.kubernetes.io/auth-type: basicnginx.ingress.kubernetes.io/auth-secret: basic-auth 指定了认证的方式为 Basic,认证秘钥为 basic-auth 。

4. 访问服务

  • 在访问主机上添加 hosts 指向集群主机

域名即为 Ingress 中配置的 hosts,这里是 longhorn.chenshaowen.com

  • 使用域名访问服务

由于 Ingress Controller 将其 80 端口映射到主机的 30914 ,因此服务的访问地址为 longhorn.chenshaowen.com:30914

上图输入账户 admin,密码 xxxxx 之后即可查看服务。如下图:


微信公众号
作者
微信公众号