Kubernetes Nginx Ingress Authentication

Kubernetes Nginx Ingress Authentication

Introduction

During managing your infrastructures, you may have a service that doesn't support authentication out of the box. Developers need to access that service or application. But also you don't want to expose it publicly to the internet since it presents some critical information. There are two options, I know, which can solve this issue. The first is to set up a VPN server in your Kubernetes cluster. And second is to use your ingress controller authentication. For example, one of the most used ingress controllers, Nginx Ingress Controller, supports basic authentication.

The first approach with VPN requires user management and server administration. It is a good choice when you plan to have this setup for a long time period. Basic authentication supported by reverse proxy is good for easy setup and to have one user.

Today I will show how to setup Basic Authentication in Kubernetes with Nginx Ingress Controller.

Setup

First, install the required package for creating a user and password file:

sudo apt-get install apache2-utils

To create a file with a password run:

htpasswd -c auth username

Where username is a name you want to use. It will ask you to provide a password twice. Make sure you choose a strong one.

Now we can start the Kubernetes part. The first step is to create a generic secret from the file we created previously.

kubectl create secret generic basic-auth --from-file=auth

Next, we need to modify the ingress YAML of our deployment. In the section of annotations add the following statements:

# 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'

And if you are developing and maintaining Helm charts for your deployments, refer to the ingress section in the values.yaml file. There you can add annotations.

Update your deployment or ingress object and after checking the domain name you must see the authentication window:

authentication-window.png

P.S So as you can see, it is not so hard to add an extra security layer to your web applications.