External authentication and authentication data forwarding with nginx

In today’s world, it is normal to see applications running on Kubernetes and exposed with ingress nginx.

Authentication can be added to any application exposed by ingress nginx by using oauth2-proxy. Using the following annotations configures nginx’s http auth request module.

nginx.ingress.kubernetes.io/auth-signin: https://oauth2-proxy-ingress/oauth2/start?rd=https://$host$request_uri$is_args$args
nginx.ingress.kubernetes.io/auth-url: https://oauth2-proxy-ingress/oauth2/auth

When a user is not authenticated, nginx will redirect them to the OAuth2 proxy, prompt for login, generate a cookie and redirect back to the application. While this protects the application, it doesn’t enable the application to know who the user is. This can be achieved by using additional configuration.

For OAuth2 proxy this means setting the --set-xauthrequest flag, which will forward headers to nginx.

With this configuration added to OAuth2 proxy additional annotations must be added:

nginx.ingress.kubernetes.io/auth-response-headers: X-Auth-Request-Email

This will result in nginx sending a header of http-x-auth-request-email to the application.

Many applications can be configured to consume this header to identify the user. For example, the popular Django framework has RemoteUserMiddleware for this exact purpose.