Logout from HTTP Authorization

This is a little trick to create a logout from your site if you are using HTTP Authentication. I am using it for a current project I’m working on where cookie based sessions won’t reliably work. We (Derek Andriesian and I) are using HTTP Authenticaton to log into an account which is only accessed through javascript and image urls from other sites. Some browsers disallow cookies being set by sites other than the current one, so keepig the user logged in is not always possible using cookie-base session management.

To use HTTP Authentication you just do this in your PHP:

// retrieve the vars passed through HTTP Auth
$user = $_SERVER['PHP_AUTH_USER'];
$pass = $_SERVER['PHP_AUTH_PW'];

function login($user, $pass) {
    // check if this is a valid login and process necessary stuff

if (!$user || !$pass || !login($user, $pass)) {
    // send the headers which will popup the login dialog
    header( 'WWW-Authenticate: Basic realm="Private"' );
    header( 'HTTP/1.0 401 Unauthorized' );
// logged in successfully

This works pretty good, however, there is no built in way to log a user out short of making them close their browser. But, you can “log them in” with a different username and password encoded into the link like so: http://username:password@www.domain.com/page.php. So, it’s possible to create a logout page by sending them to a link http://x:x@www.domain.com/logout.php. Then you may redirect them somewhere else, and as long as you don’t have a user with a username and password of ‘x’ and ‘x’ then they will be logged out of any valid account.

5 Responses to “Logout from HTTP Authorization”

  1. Gary Matthew Rogers » Blog Archive » Logout from HTTP Authorization Says:

    […] http://www.jacwright.com/blog/37/logout-from-http-authorization/ […]

  2. Arun Kapil Says:

    This methodology while fantastic, fails with Internet Explorer running on Windows.

    Microsoft disabled the use of usernames and passwords encoded into links on July 11, 2005. You can read all about it here: http://support.microsoft.com/default.aspx?scid=kb;en-us;Q834489

  3. Jacob Wright Says:

    Thank you for the info. That’s too bad. Well, I suppose there is always, uh, well, forget about logging out. :)

  4. Seva Gluschenko Says:

    The idea which came into my mind recently brings the logout idea back to the reality as follows:

    1. Logout link sends user to a page which sets him a cookie “Logged out”.

    2. When user with such a cookie tries to access the protected realm next time, we send him 401.

    What is unclear to me in this issue is the moment we can reset the cookie

  5. Green FiLin Says:

    Thank you for good trick!