Skip to main content

Conditional HTTP Basic Auth in Apache 2.4

This blog post might be outdated!
This blog post was published more than one year ago and might be outdated!
· 2 min read
Stephan Hochdörfer
Head of IT Business Operations

One of our internally used application uses HTTP Basic auth to authenticate a user against our LDAP instance. In a recent attempt I had the need to expose one endpoint publicly without the need of an authentication. I tried several solutions but each of them did not work for my specific use case. At first I tried several Location directives but that did not work as expected. I also tried the LocationMatch directive which also did not work. By accident I came across a blog post stating that Apache 2.4 supports if/else style syntax and that seemed to work fine for me.

<VirtualHost *:80>
DocumentRoot /srv/app/web/

ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined

<Directory /srv/app/web/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>

<Location />
<If "%{THE_REQUEST} =~ m#^POST /my/trigger#i">
# No authentication needed
Require all granted
</If>
<Else>
# authnz_ldap logic here...
</Else>
</Location>
</VirtualHost>

The if tag supports different expressions to evaluate data. You can use binary operators, different functions or regular expressions. In the example above I used a regex because the trigger url for my specific use case can contain different parameters. The expressions syntax also supports variables like REQUEST_URI or PATH_INFO. Due to some rewrite logic neither of those contained the requested url. Thus I had to use the THE_REQUEST variable. On the plus side this also gave me the chance to check for the HTTP method involved, making it possible to expose the url just for POST requests.