basic-authenticationhaproxy

HAProxy get username associated with Basic Auth


I am currently using HAProxy's http-request auth operation to conditionally restrict access to resources. I would like to go on to add the username associated with a successful authorisation to the headers of the request being passed to the backend, emulating the Apache environment variable HTTP_AUTH_USER.

I am able to get the group associated with the operation by way of http_auth_group but would much rather have the username.

I appreciate I could move this operation to the web servers but I would rather not administer a small number usernames and passwords on 10s of machines when I can do it in 2 places via the proxy.


Solution

  • The http_auth_group layer 7 sample fetch is a little bit confusingly named at first glance, with the word "group" appearing in it, implying that it returns the group. In fact, it takes the group as its argument and returns no value unless the request has been authenticate with the credentials of a member of the specified group... in which case, it returns the username.

    So it has two purposes: testing its truthiness to determine whether any member of the group has authenticated the request, or extracting the username. So...

    http-request set-header X-Username %[http_auth_group(GROUP_NAME)]
    

    ...will remove any X-Username: header (case-insensitive) in the incoming request (if already present), and populate a new X-Usernane: header with the username of the authenticated user, or a blank value otherwise (if your config allows anonymous requests).

    It's important to use set-header, not add-header, because adding the header will not remove any matching header in the incoming request, which presents a security risk. Always set unless you have a specific reason to add, instead.