in Coding

Basic Auth log-out with JavaScript

Whenever you have a log-in on your site, the chance is high that you also want to have a log-out. The easiest way to do a log-in is to use HTTP’s Basic Auth. But how to do a log-out with Basic Auth?

Basic Auth credentials are cached until the browser is closed

The problem with logging out from Basic Auth is simple: the browser will cache your credentials by default until the browser windows is closed. There is no standard mechanism to invalidate them. So Basic Auth doesn’t allow a log-out!

The dirty hack

However, there is always a dirty hack and this one goes like this: Instead of logging out, we do the opposite and try to do another login. But this time, we use a wrong user/password which will cause a 401 Unauthorized exception in our browser. But more important, it will replace our authenticated user with the new (and wrong) user in the cached Basic Auth credentials of our browser. After that, we are effectively logged out!


Best regards,

Write a Comment


  1. This does not work as it seems that Chrome does not allow sync requests anymore. It also does not work asynchronously either. It just calls the page as expected but the session is still valid.

  2. Hello, too dirty I think, I would never use a get method for login or logout, should be a POST instead, specially if you will send credentials over it.

    • HTTP Basic Auth sends the credentials in a header regardless of the verb, so that doesn’t make a difference.