TL;DR
You can add Basic authentication after mutual TLS (mTLS) for an extra layer of security. mTLS verifies the client’s identity using certificates, while Basic auth requires a username and password. This guide shows you how to configure this in Nginx.
Setting up mTLS with Basic Authentication
- Configure mTLS First: Ensure your Nginx server is already correctly set up for mutual TLS authentication. This involves having client certificates, configuring the
ssl_certificateandssl_certificate_keydirectives, and verifying client certificates in your configuration file. - Enable Basic Authentication: Add a new location block within your Nginx configuration to handle Basic authentication. This block should come *after* your mTLS configuration block so that mTLS is performed first.
- Create a Password File: Use the
htpasswdutility to create a password file. This file stores usernames and encrypted passwords.htpasswd -c /etc/nginx/.htpasswd username1Repeat for each user you want to authenticate.
- Configure Nginx Location Block: Add the following location block to your Nginx configuration file (typically in
nginx.confor a separate site configuration file):location /secure-area { auth_basic "Restricted Access"; auth_basic_user_file /etc/nginx/.htpasswd; proxy_pass http://your_backend_server; # Replace with your backend server address } - Restart Nginx: After making changes to the configuration file, restart Nginx to apply them.
sudo systemctl restart nginx - Test Authentication: Access the protected area (e.g.,
https://yourdomain.com/secure-area) in your browser. You should be prompted for a username and password before being allowed access. Make sure your client certificate is also presented during this process.
Important Considerations
- Order Matters: The order of configuration blocks in Nginx is crucial. mTLS must be configured *before* Basic authentication to ensure that only authenticated clients (via certificates) are then prompted for credentials.
- Security Best Practices: While adding Basic auth after mTLS increases security, remember that Basic auth transmits credentials in base64 encoding which can be intercepted if not using HTTPS. Always use HTTPS with Basic authentication.
- Alternative Authentication Methods: Consider more robust authentication methods like OAuth 2.0 or OpenID Connect for production environments instead of relying solely on Basic authentication.