如何向k8s服务添加身份验证

时间:2020-08-04 11:58:37

标签: authentication kubernetes-ingress nginx-ingress

我有一个类型为NodePort的应用程序。 是否可以在不重写部署的情况下添加身份验证? 也许有一个简单的yaml入口示例可以做到这一点?

1 个答案:

答案 0 :(得分:1)

NGINX Ingress Controller有很多身份验证方式,例如最简单的Basic Authentication,它使用包含htpasswd生成的文件的机密。

创建秘密:

$ htpasswd -c auth foo
New password: <bar>
New password:
Re-type new password:
Adding password for user foo
$ kubectl create secret generic basic-auth --from-file=auth
secret "basic-auth" created
$ kubectl get secret basic-auth -o yaml
apiVersion: v1
data:
  auth: Zm9vOiRhcHIxJE9GRzNYeWJwJGNrTDBGSERBa29YWUlsSDkuY3lzVDAK
kind: Secret
metadata:
  name: basic-auth
  namespace: default
type: Opaque

要在Ingress规则中使用:

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: ingress-with-auth
  annotations:
    # type of authentication
    nginx.ingress.kubernetes.io/auth-type: basic
    # name of the secret that contains the user/password definitions
    nginx.ingress.kubernetes.io/auth-secret: basic-auth
    # message to display with an appropriate context why the authentication is required
    nginx.ingress.kubernetes.io/auth-realm: 'Authentication Required - foo'
spec:
  rules:
  - host: foo.bar.com
    http:
      paths:
      - path: /
        backend:
          serviceName: http-svc
          servicePort: 80

ingress-nginx auth examples page

中也提供了示例