Basic Authentication with FastCGI

HTTP Basic authentication is a quick and simple way of authenticating access to a web service API. As long as it is used alongside TLS/SSL encryption it is just as secure as traditional web forms.

However I recently had to wrestle with an unusual situation where no matter what credential I supplied they simply would not be accepted. It turned out that the PHP_AUTH_USER and PHP_AUTH_PW superglobals were empty.

Traditionally Apache would handle the authentication using a .htpasswd file. For security Apache does not pass credentials to external CGI scripts, to prevent external potential malicious scripts stealing login credentials. However, in my case I want to use PHP to perform the authentication, this is because I am using my existing authentication system which stores credentials in the database and logs failed login attempts, features which are difficult to implement using Apache alone.

To populate the PHP superglobals we have to instruct Apache to pass the authentication credentials to PHP, by placing the following in your .htaccess file

<IfModule mod_rewrite>
    RewriteEngine On
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

This tells Apache to pass the HTTP Authorization header through to the PHP runtime, and basic auth now works!

This only affects PHP via FastCGI and not mod_php.