Menü schliessen
Created: November 18th 2024
Last updated: December 19th 2024
Categories: Common Web Development
Author: Tim Fürer

HTTP: Simple .htaccess Alternative to Basic Auth

Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

HTTP basic access authentication is a great way to quickly restrict access to areas (or even the entirety) of a web server to unauthorised users at an overall passable degree of security. However, some clients, browsers, and firewalls lack support for (usually due to missing UI) or block basic auth, rendering certain users incapable of ever accessing the restricted content, even if they're technically in possession of the right credentials to authenticate.


A Convenient Alternative: Implementation

We've found a minimal solution using query parameters and cookies that, for our use case, was adequate as an alternative to basic auth, not requiring any login screen and enabling virtually all clients to authenticate. The concept of the approach is pretty much globally applicable, but we'll showcase our implementation using Apache and .htaccess:

RewriteEngine On

RewriteCond %{QUERY_STRING} !^access_key=my-password$ [NC]
RewriteCond %{HTTP_COOKIE} !access_key=my-password
RewriteRule ^ - [R=511,L]

Header set Set-Cookie "access_key=my-password; path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Strict"

Be sure to place the code at the beginning of the .htaccess file and to change out the 3 instances of "my-password" in the code to whatever the password should be. Since we're storing the password in plain text (not hashed) here, we recommend avoiding use of any sensitive password. Once authenticated, access lasts for an hour (or 3600 seconds), but that expiration timer is refreshed on every connection while still authenticated.


How to Use

When implemented, if you visit any part affected by the .htaccess, you should get a 511 response "Network Authentication Required". To gain access, append the GET-parameter "access_key" to the visited URL and set it to your password. For example: https://foobar.com?access_key=my-password. While authenticated, you needn't add the parameter to the URL again, as authentication is kept track of by the server through a cookie.