Warm tip: This article is reproduced from serverfault.com, please click

How to setup basic auth in ingress for included url rules?

发布于 2020-11-23 14:38:31

I have a project on k8s with 3 services, that I want to cover with basic auth, and 1 service that I'd like to be public. In ingress 4 services devided by url rules, that have different prefixes. I had found tutorial about basic auth setup in ingress for all rules, but not about excluded, included urls.

Questioner
Oleksiy
Viewed
0
PjoterS 2020-12-01 22:30:25

Unfortunately GCP Ingress does not provide basic auth authentication as this feature is specific for Nginx Ingress.

As workaround for basic auth in GCP Ingress you can use IAP. Detailed How To information can be found in Enabling IAP for GKE article.

If you would still like to use Nginx Ingress basic auth you can do it on GKE but you need specify nginx annotation.

metadata:
  name: foo
  annotations:
    kubernetes.io/ingress.class: "nginx"

Regarding using basic auth on only one service out of four, you can createa 2 Ingress. Very similar issue was discussed in another stackoverflow thread, which contains good solution - Nginx-ingress Kubernetes routing with basic auth.

Basic Auth Ingress

First Ingress should be without annotations:

  • nginx.ingress.kubernetes.io/auth-type
  • nginx.ingress.kubernetes.io/auth-secret
  • nginx.ingress.kubernetes.io/auth-realm

Second Ingress should contain proper annotations and should look similar to below YAML.

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: auth-ingress
  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'
    #cert-manager.io/cluster-issuer: if you would use cert manager like letsencrypt
spec:
  tls:
    - hosts:
        - example.com
      secretName: example-tls
  rules:
    - host: example.com
      http:
        paths:
          - path: /auth
            backend:
              serviceName: auth-service
              servicePort: <auth-service-port>

Aditional information

There is an option to deny all traffic to specific path. It can be achieved by configuration-snippet annotation.

   annotations:
      nginx.ingress.kubernetes.io/configuration-snippet: |

      location /specificpath {

           deny all;  
      }