Shibu
Shibu

Reputation: 115

How can I put basic auth on specific HTTP methods in ngnix ingress?

I can create ingress with basic auth. I followed the template from kubernetes/ingress-nginx:

apiVersion: extensions/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

It works fine, but I need to allow 'OPTIONS' method without basic auth for pre-flight requests. Any pointers on how to do it will be very helpful.

Upvotes: 6

Views: 2010

Answers (2)

Ostecke
Ostecke

Reputation: 1769

I had the same issue: an application configured for CORS, yet behind a k8s nginx ingress with basic authentication which kills the preflight requests. In the end I moved my CORS configuration to the ingress. The annotations on the ingress work together perfectly; responding to the preflight requests in the correct way. This solved my issue.

    nginx.ingress.kubernetes.io/auth-type: basic
    nginx.ingress.kubernetes.io/enable-cors: "true"

Also see https://github.com/kubernetes/ingress-nginx/issues/8964

Upvotes: 0

adroste
adroste

Reputation: 887

I just encountered the same problem. I solved it by using a configuration-snippet.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: my-cors-auth-ingress
  annotations:
    nginx.ingress.kubernetes.io/configuration-snippet: |
      # fix cors issues of ingress when using external auth service
      if ($request_method = OPTIONS) {
        add_header Content-Length 0;
        add_header Content-Type text/plain;
        return 204;
      }
      more_set_headers "Access-Control-Allow-Credentials: true";
      more_set_headers "Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS";
      more_set_headers "Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization";
      more_set_headers "Access-Control-Allow-Origin: $http_origin";
      more_set_headers "Access-Control-Max-Age: 600";
    nginx.ingress.kubernetes.io/auth-url: "http://auth-service.default.svc.cluster.local:80"

Upvotes: 3

Related Questions