kubernetes ingress添加basic auth认证
创建认证文件
通过htpasswd工具生成用户密码文件
# htpasswd是apache httpd工具包中的工具
# 安装htpasswd
## centos
yum install httpd-tools -y
## ubuntu
apt install apache2-utils -y
# 创建认证文件
[root@vm ~]# htpasswd -c authfile admin
New password:
Re-type new password:
Adding password for user admin
# 查看文件内容
[root@vm ~]# cat authfile
admin:$apr1$o3a5s2NV$KZAEAoFPQaTvaAta887lB1
创建secret
# 将authfile内容创建为名为basic-auth的secret
[root@vm ~]# kubectl -n apm create secret generic basic-auth --from-file=authfile
secret/basic-auth created
# 查看secret/basic-auth内容
[root@vm ~]# kubectl get secret/basic-auth -o yaml -n apm
apiVersion: v1
data:
authfile: YWRtaW46JGFwcjEkbzNhNXMyTlYkS1pBRUFvRlBRYVR2YUF0YTg4N2xCMQo=
kind: Secret
metadata:
creationTimestamp: "2020-04-10T09:21:55Z"
name: basic-auth
namespace: default
resourceVersion: "935267"
selfLink: /api/v1/namespaces/default/secrets/basic-auth
uid: b5b2c37d-b961-4e75-b43f-ccfbb72885e4
type: Opaque
创建ingress
注意:只有0.9.0以上版本的nginx-ingress-controller才支持basic认证。
# 配置主要通过ingres的annotations(注解)来定义
# nginx.ingress.kubernetes.io/auth-type 认证类型
# nginx.ingress.kubernetes.io/auth-secret 认证文件,也就是上面创建的secret名称
# nginx.ingress.kubernetes.io/auth-realm 指定认证文件中的用户(认证文件可以有多个用户)
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
annotations:
nginx.ingress.kubernetes.io/auth-type: basic
nginx.ingress.kubernetes.io/auth-secret: basic-auth
nginx.ingress.kubernetes.io/auth-realm: '"Authentication Required - admin"'
name: kibana
namespace: apm
spec:
rules:
- host: kibana.gisuni.dev
http:
paths:
- backend:
serviceName: kibana
servicePort: 5601
tls:
- hosts:
- kibana.gisuni.dev
secretName: gisuni-dev
访问测试
- 浏览器访问kibana.gisuni.dev
- 弹出basic auth认证框
- 输入admin用户和密码后,可以正常访问应用