Published: 20/08/20

How can you logout of an HTTP Auth session??

So it turns out the mighty HTTP auth protocol doesn't allow users to logout! If you're reading this its probably because you've found this answer on Stack overflow to some rather now dated questions, but still just as relevant. Here is a 2020 version which will hopefully last for a few years and gives you an easy to use logout solution to the HTTP authentication method. It uses Jquery however you may use plain Javascript.

1. Protect your folder

I'm protecting a subdirectory with the following .htaccess file:

AuthName "Dialog prompt"
AuthType Basic
AuthUserFile /path/to/htpasswd/.htpasswd
Require valid-user

SSLOptions +StrictRequire
SSLRequire %{HTTP_HOST} eq ""

This is fairly standard and forces the user to connect via SSL to the website. Note the AuthName as this will be replace/overwritten later on.

2. Create a folder (I created it within the protected folder) called logout

Once you've created the subfolder add the following .htaccess file:

AuthName "Dialog prompt"
Require user logout

Thanks to this q/a for the requiring a different user

3. Create your logout script

My file is called logout.html and sits in the main protected folder.

Use the below JS (as mentioned, relies on Jquery):

	// Call the page - which will naturally return a 401 error
		type: "GET",
		url: '/training/logout',
		dataType: 'json',
		username: 'byebye',
		password: 'byebye',

		window.location.href = '/';

Notice, we are using an incorrect user/password. As such the browser never triggers the popup for the login area but instead rejects it as a failure. Notice also that Jquery ajax doesn't return an error. As such we set a timeout and do a redirect.

And that folks - is how you can logout of HTTP Authenticated logins with a couple of .htaccess files and a javascript based logout.