How to logout user for basic HTTP authentication

15,107

Solution 1

Yes, but it's not very smooth.

You have a special script URL (eg /logout; like a login script it must be in the root of the webapp to ensure the auth gets set to the right path), which, instead of requiring a valid username/password to proceed, requires an invalid one.

So the logged-in user hits /logout, sending valid credentials in the Authorization header. Your script responds 401, and the browser pops up a username/password prompt. You tell the user to put false values in (or, in most browsers, just leaving it blank is OK too) and hit OK. This replaces the valid stored credentials with invalid ones. Your script then returns a ‘logged out’ page or a redirect back to the home page, and the user is no longer logged in.

(Care: Safari, sadly, passes every HTTP request without any credentials first, only trying again with stored credentials if it gets a 401 response. This means you shouldn't take a request with no Authorization header as being OK for the logout script; it must be present, even if with blank credentials in it. This unfortunate behaviour also means you can't provide a logged-in and not-logged-in version of the same page to Safari users under the same URL, and it makes Safari slow at browsing Basic-protected sites, since every page request has to happen twice.)

There is another way that is sometimes used: use JavaScript to send an XMLHttpRequest with a fake username/password combo (eg xhr.open('GET', '/app', true, '_', '_')). This has the non-standard side-effect of replacing the stored credentials in IE and Firefox (but not Opera; not sure about the others).

[Ugh. This is a pain. No wonder everyone uses cookies instead...]

Solution 2

A solution proposed in an answer to another question is to point the logout link to a URL that contains fake credentials e.g. http://log-me-out:[email protected]/logout

Share:
15,107
Dhaval
Author by

Dhaval

Updated on June 04, 2022

Comments