Basic Authentication For Ingress Host

Basic Auth is a way to require a username and password to access a resource. In an Ingress setup, this can be used to protect access to HTTPS endpoints, like web applications or APIs. By adding Basic Auth to your Ingress resource, you can control who has access to your application or service and ensure that only authorized users can access it.

To enable Basic Authentication for an Ingress rule, create a secret that includes a file generated with htpasswd. This file must be named "auth" and stored as a key within the secret. If these conditions are not met, the ingress controller will produce an error.

Create auth file using htpasswd,

You can change the user with your user name.

$ htpasswd -c auth user 
New password:
Re-type new password:
Adding password for user user

The file auth was created with your credentials.

Create Kubernetes secret from the auth file,

$ kubectl create secret generic basic-auth --from-file=auth
secret "basic-auth" created

Kubernetes secret was created with the name basic-auth.

$ kubectl get secret basic-auth -o yaml

apiVersion: v1
data:
  auth: YXNkZjoxMjM0NTY3ODkwJFM5NjJDb2RlQXBwbGljYXRpb24K
kind: Secret
metadata:
  name: basic-auth
  namespace: default
type: Opaque

To enable basic authentication for a host in Kubernetes, you can edit the ingress.yaml or ingress manifest and add the necessary annotation.

annotations:
  # authentication type
  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 - user'

Apply the changes using the kubectl command.

To ensure your basic authentication is working, try accessing the host in a web browser — if it’s set up correctly, you’ll be prompted to enter valid login credentials.