haproxy forcing a redirect to login and redirect back

I have a website http://blahblah.com I want to add a login page before anything from http://blahblah.com . I have written some simple login code in php. The issue is that I can't modify the code in blahblah , it some microservice written in rust and other languages.

In login.php, i can redirect to blahblah.com as needed. I know i can force haproxy to redirect to my-login.com if people come to blahblah.com , and then in my-login.com i could redirect to blahblah.com but this could end up in circles.

Can someone help/give me tips on what the haproxy config should be like to make this work?


Solution 1:

HAProxy may not be the best tool for this, but hard to say without understanding your architecture and usage better. Anyway, one of the ways is to use a map function to choose the correct backend.

See https://www.haproxy.com/blog/introduction-to-haproxy-maps/, but roughly you would do something like

frontend frontend-blahblah
 bind *:443
 use_backend %[req.hdr(x-app-auth),map(/mnt/resource/token.map,backend-unauth)]

The map file /mnt/resource/token.map would have a list of authentication keys which each map to the backend-auth backend (i.e. blahblah.com). Anyone without an authentication key is sent to backend-unauth (i.e. your login server).

You would additionally need to do the following:

  1. The app would have to send the X-App-Auth header with each request in this example. Or change it to use cookies instead like req.cook(APPAUTH).
  2. When a user logs in or out, the map file in /mnt/resource/token.map would need to be updated by your login server. See the article referenced above for several ways to do this. Perhaps the easiest is to use http-request set-map and http-request del-map and restrict access to the IP of your login server, e.g. have HAProxy listen on a separate 'management port' and reject requests from other IPs plus any other security. For example, your login server might make a call to https://blahblah.com:8443/add-token/123456789... to add an authentication key.
  3. The login server will need to take care of setting the cookie/returning the authentication key to the client. There's probably some cross-site issues which means some HAProxy header adjustment might be needed; you may have already considered and resolved those.

All of this is a blunt instrument - a user is logged in and has permission to access the site or not. There's not much granularity differentiating users; if you want that, you could be better off putting your login server in front of the other site as a proxy.