OPNsense HAProxy And Authentik Integration: Configuration And Troubleshooting
In this article, we delve into the intricacies of configuring HAProxy on OPNsense to work seamlessly with Authentik for robust authentication. Many users, like yourself, have found the initial setup challenging, and the aim here is to provide a comprehensive guide that not only clarifies the process but also offers a full HAProxy configuration example to serve as a practical reference. We will explore common pitfalls and troubleshooting steps to ensure a smooth implementation.
The integration of OPNsense, HAProxy, and Authentik presents a powerful solution for securing web applications. OPNsense, a feature-rich, open-source firewall and routing platform, provides the network foundation. HAProxy, a high-performance load balancer, efficiently distributes traffic and enhances application availability. Authentik, an open-source identity provider, adds a crucial layer of authentication and authorization.
The challenge lies in orchestrating these components to work harmoniously. HAProxy must be configured to correctly forward authentication requests to Authentik and then authorize users based on Authentik's response. This involves setting up the appropriate access control lists (ACLs), backend servers, and frontend listeners within HAProxy. A misconfiguration in any of these areas can lead to authentication failures or security vulnerabilities. This guide provides you with a step-by-step methodology to ensure a secure and efficient setup.
Before diving into the configuration, let's establish a clear understanding of the key concepts and components involved:
- HAProxy Frontends: These define how HAProxy listens for incoming connections. A frontend typically binds to a specific IP address and port and specifies the rules for handling requests.
- HAProxy Backends: These define the servers that HAProxy will forward traffic to. In this case, the backend will include the Authentik server.
- Access Control Lists (ACLs): ACLs are used to make decisions based on request attributes, such as the URL path or HTTP headers. They are crucial for directing authentication requests to Authentik.
- Authentik: This is the identity provider responsible for authenticating users. It handles the login process and provides authentication tokens or cookies.
- OIDC/OAuth2: These are authentication protocols that Authentik uses. HAProxy needs to be configured to handle the redirects and token exchanges involved in these protocols.
Now, let's walk through the configuration process step by step. This guide assumes you have OPNsense, HAProxy, and Authentik installed and running. If not, refer to their respective documentation for installation instructions.
Step 1: Configure Authentik
First, you need to configure Authentik to work with HAProxy. This involves creating an application and a provider within Authentik.
- Create an Application: In Authentik, create a new application that represents the service you want to protect with HAProxy. This application will have a unique Client ID and Client Secret.
- Create a Provider: Create an OAuth2/OIDC provider for the application. Configure the Redirect URIs to point to your HAProxy instance. For example, if your HAProxy instance is accessible at
https://haproxy.example.com
, the Redirect URI might behttps://haproxy.example.com/_oauth/callback
. This URI is crucial as it's where Authentik will redirect users after successful authentication. - Note Client ID and Secret: Make a note of the Client ID and Client Secret. You'll need these when configuring HAProxy.
Step 2: Configure HAProxy Frontends
Next, configure the HAProxy frontend to listen for incoming requests and direct authentication requests to Authentik.
- Create a Frontend: In the OPNsense web interface, navigate to Services -> HAProxy -> Frontend and create a new frontend.
- Bind to Address and Port: Specify the IP address and port on which HAProxy should listen. For example, you might bind to the public IP address on port 443 for HTTPS traffic.
- Enable SSL Offloading: If you're using HTTPS, enable SSL offloading and configure the SSL certificate. This will allow HAProxy to handle the SSL encryption and decryption, reducing the load on your backend servers.
- Define ACLs: Create ACLs to identify requests that need authentication. For example, you might create an ACL that matches requests to specific URL paths or domains. A crucial ACL is one that checks for the presence of a valid authentication cookie. If the cookie is missing or invalid, the request should be redirected to Authentik for authentication.
Step 3: Configure HAProxy Backends
Now, configure the HAProxy backend to forward traffic to your backend servers and to Authentik.
- Create a Backend for Authentik: Create a backend that points to your Authentik server. Specify the IP address and port of your Authentik instance. This backend will be used for authentication requests.
- Create a Backend for Your Application: Create a backend that points to your application servers. This is where HAProxy will forward traffic after successful authentication.
- Configure Health Checks: Configure health checks for both backends to ensure that HAProxy only forwards traffic to healthy servers. This is especially important for production environments.
Step 4: Configure HAProxy Rules
This is where you define the rules that determine how HAProxy handles incoming requests.
- Redirect Unauthenticated Users: Create a rule that redirects unauthenticated users to Authentik. This rule should use the ACLs you defined earlier to identify unauthenticated requests. The redirect URL should point to Authentik's authorization endpoint, including the Client ID and Redirect URI.
- Handle Authentik Callback: Create a rule to handle the callback from Authentik after successful authentication. This rule should exchange the authorization code for an access token and set a cookie in the user's browser. The cookie will be used to authenticate subsequent requests.
- Forward Authenticated Requests: Create a rule that forwards authenticated requests to your application backend. This rule should use the ACL that checks for the presence of a valid authentication cookie.
Step 5: HAProxy Configuration Example
Here's a full HAProxy configuration example that you can adapt to your specific setup:
# Global settings
global
log 127.0.0.1 local2
chroot /var/run/haproxy
pidfile /var/run/haproxy.pid
maxconn 4000
user haproxy
group haproxy
daemon
# turn on stats unix socket
stats socket /tmp/haproxy.sock level admin
defaults
mode http
log global
option httplog
option dontlognull
option http-server-close
option forwardfor except 127.0.0.0/8
option redispatch
retries 3
timeout http-request 10s
timeout queue 1m
timeout connect 10s
timeout client 1m
timeout server 1m
timeout http-keep-alive 10s
timeout check 10s
maxconn 3000
# Frontend for HTTPS traffic
frontend https-frontend
bind *:443 ssl crt /path/to/your/certificate.pem
mode http
option tcplog
# ACL to check if the user is authenticated
acl is_authenticated http_req_header Cookie auth_session
# ACL to match the OAuth2 callback URL
acl is_oauth_callback path /_oauth/callback
# Redirect unauthenticated users to Authentik
http-request redirect code 303 location https://authentik.example.com/application/o/authorize/?client_id=YOUR_CLIENT_ID&response_type=code&scope=openid profile email&redirect_uri=https://haproxy.example.com/_oauth/callback unless is_authenticated OR is_oauth_callback
# Handle OAuth2 callback
use_backend authentik-callback if is_oauth_callback
# Forward authenticated requests to the backend
default_backend your-application-backend
# Backend for Authentik callback
backend authentik-callback
mode http
http-request set-header X-Original-URL %[url]
http-request set-header X-Original-Host %[host]
server authentik 127.0.0.1:9000 # Replace with your Authentik server address and port
# Backend for your application
backend your-application-backend
mode http
server your-application 127.0.0.1:8080 # Replace with your application server address and port
# Backend for Authentik (if needed for direct access)
backend authentik-backend
mode http
server authentik 127.0.0.1:9000 # Replace with your Authentik server address and port
Note: Replace the placeholder values (e.g., /path/to/your/certificate.pem
, YOUR_CLIENT_ID
, https://authentik.example.com
, https://haproxy.example.com
, 127.0.0.1:9000
, 127.0.0.1:8080
) with your actual values.
Step 6: Troubleshooting and Common Issues
If you encounter issues, here are some common problems and troubleshooting steps:
- Redirect Loops: If you're stuck in a redirect loop, double-check your ACLs and redirect rules. Make sure you're not redirecting requests unnecessarily.
- Authentication Failures: If authentication is failing, check your Authentik configuration, especially the Redirect URIs and Client ID. Also, verify that HAProxy is correctly forwarding authentication requests to Authentik.
- Cookie Issues: If the authentication cookie is not being set or recognized, check your HAProxy rules for handling the Authentik callback. Ensure that the cookie is being set with the correct domain and path.
- SSL Errors: If you're encountering SSL errors, verify that your SSL certificate is correctly configured in HAProxy.
- HAProxy Logs: Check the HAProxy logs for error messages. The logs can provide valuable insights into what's going wrong.
To ensure a secure and performant setup, consider the following best practices:
- Use HTTPS: Always use HTTPS to encrypt traffic between the client, HAProxy, and your backend servers.
- Regularly Update: Keep OPNsense, HAProxy, and Authentik updated with the latest security patches.
- Monitor Performance: Monitor HAProxy's performance and resource usage to identify potential bottlenecks.
- Secure Cookies: Set the
Secure
andHttpOnly
flags on your authentication cookies to prevent them from being accessed by JavaScript or transmitted over non-HTTPS connections.
Configuring HAProxy on OPNsense to work with Authentik requires careful attention to detail, but the resulting setup provides a robust and secure authentication solution. By following this comprehensive guide and using the provided configuration example, you can successfully integrate these components and protect your web applications. Remember to adapt the configuration to your specific environment and to follow best practices for security and performance. This detailed guide ensures you understand the key aspects of the configuration and can effectively troubleshoot any issues. By implementing this setup, you are not only securing your applications but also gaining a deeper understanding of modern authentication workflows.