http basic authentication "log out"

JavascriptHttpLogoutBasic Authentication

Javascript Problem Overview


HTTP basic authentication credentials are stored until the browser is closed, but is there a way to remove the credentials before the browser is closed?

I read about a trick with HTTP 401 status code, but it seems to work not properly (see comment to answer). Maybe the mechanism trac uses is the solution.

Can the credentials be deleted with JavaScript? Or with a combination of JavaScript and the status 401 trick?

Javascript Solutions


Solution 1 - Javascript

Update: This solution does not seem to work anymore in many browsers. Kaitsu's comment:

> This solution of sending false credentials to make browser forget the correct authenticated credentials doesn't work in Chrome (16) and IE (9). Works in Firefox (9).


Actually you can implement a workaround by sending false credentials to the service. This works in Browsers by sending another (non-existent?) Username without a password. The Browser loses the information about the authenticated credentials.

Example:

> https://www.example.com/ => Log in > with basic auth as "user1"

> Now open > > https://[email protected]/ > > You're Logged out. ;)

Regards

P.s.: But please test this with all needed Browsers before you rely on the given information.

Solution 2 - Javascript

Expanding on Jan.'s answer, and updating owyongsk's answer:

Here is some example jquery java-script code to cause the browser to essentially send a bogus login request to the page your trying to protect, which in all tested browsers caused the cached credentials to be removed, then redirects the user to a non-protected page.

The alert() when something goes wrong should probably be changed to something else.

//Submits an invalid authentication header, causing the user to be 'logged out'
function logout() {
    $.ajax({
    	type: "GET",
		url: "PUT_YOUR_PROTECTED_URL_HERE",
		dataType: 'json',
		async: true,
		username: "some_username_that_doesn't_exist",
		password: "any_stupid_password",
		data: '{ "comment" }'
	})
//In our case, we WANT to get access denied, so a success would be a failure.
.done(function(){
	alert('Error!')
})
//Likewise, a failure *usually* means we succeeded.
//set window.location to redirect the user to wherever you want them to go
.fail(function(){
	window.location = "/";
	});
}

Then it was as easy as just having the logout link call the logout() function, and it seemed to work seamlessly to the user, though it is still technically a hack job.

Solution 3 - Javascript

You can try a hack that is working at the moment with the latest Chrome and Firefox. Create a "/logout" page on your server which accepts only a certain credential such as username: false, password: false. Then using this AJAX request below, you can send the user to that page.

  $("#logout").click(function(e){                                              
    e.preventDefault();                                                        
    var request = new XMLHttpRequest();                                        
    request.open("get", "/logout", false, "false", "false");                                                                                                                               
    request.send();                                                            
    window.location.replace("WHEREVER YOU WANT YOUR LOGGED OUT USER TO GO");                                              
  });

What happens is that the false username and password is cached from the valid XMLHttpRequest instead of the current user's credentials, and when a user tries to login into any page, it will use the cached fake credentials, failing to authenticate, it will ask the user to enter another one. Hope this helps!

Solution 4 - Javascript

just finishing an implementation that worked fine to me: At the server I evaluate Session, User Name and password, so I keep track of that information, the login algoritm is as follows:

1.Check if user and password is not empty, else return 401.

2.Check if we have registered the session in our logged-in user list, if not then check if user and password is valid and if so save session id in our list, then return 401. I'll explain this step: if the session id is different one of three things happened: a) The user is opening another window. b) The user session has finished, ie user logged out. c) The session expired due to inactivity. But we want to save the session as long as the user credentials are valid but return a 401 to ask once for password, if we don't save the session then the user could never log in because we don't have the new session id in our list.

3.Check if user credentials are right, if so, save session info and continue serving pages, else return 401.

So, the only thing I have to logout a user is to close the session at the server when the user requests the logout page and the web browser shows again the login dialog.

I'm thinking as I write this that there has to be a step where the program checks if the user is already logged to avoid impersonation, maybe I can save more than one session id per user to allow multiple session, well, I would like your comments about it.

Hope you get the idea, and comment if you see any security flaw ;)

Solution 5 - Javascript

You can delete credentials with JavaScript:

    $("#logout").click(function(){
        try {
            document.execCommand("ClearAuthenticationCache");
            window.location.href('/logout.html'); // page with logout message somewhere in not protected directory
        } catch (exception) {}
    });

This code works only in IE. This is the reason why try/catch block is added there. Also, for the same reason the logout link you should show for IE users only:

    <!--[if IE]>
        <div id="logout">[Logout]</div>
    <![endif]-->

And for other users my suggestion is something like:

    <div id="logout2" onclick="alert('Please close your browser window to logout')">[Logout]</div>

Solution 6 - Javascript

If you have control over the server code, you can create a "logout" function that replies "401 Unauthorized" regardless of the credentials given. This failure forces browsers to remove saved credentials.

I just tested this with Chrome 34, IE 11, Firefox 25 - using Express.js server and HTTP basic authentication.

Solution 7 - Javascript

What has worked for me in Chrome (Version 66) is to send an Ajax request to an URL that returns 401. That way the basic authentication cache seems to be cleared.

var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/url_that_returns_401", true);
xhttp.send();

Solution 8 - Javascript

This codes worked for me in Chrome (version 83):

var xhttp = new XMLHttpRequest(); 
xhttp.open("GET", "/url_that_return_401", true); 
xhttp.setRequestHeader('Authorization', 'Basic '); 
xhttp.send();

Need to execute this code (maybe by button click or console window) and then prompt appeared, you need to press Cancel button. Then authentication fields clears and you can refresh page and login in with another credentials.

Solution 9 - Javascript

Mark the nonce as invalid. I did an Ajax call to the server side asking to logout. The server side gets the "Authenticate: Digest..." request in a header. It extracts the nonce="" from that line and adds it to a list of disabled nonces. So next time the browser sends that a request with that "Authenticate: Digest..." line the server replies with 401. This makes the browser ask the user for a new userid/password.

Works fine for my application but only for Digest authentication.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondeamonView Question on Stackoverflow
Solution 1 - JavascriptJan.View Answer on Stackoverflow
Solution 2 - Javascript1n5aN1aCView Answer on Stackoverflow
Solution 3 - JavascriptowyongskView Answer on Stackoverflow
Solution 4 - JavascriptErwinView Answer on Stackoverflow
Solution 5 - JavascriptVilius GaidelisView Answer on Stackoverflow
Solution 6 - JavascriptGreg TView Answer on Stackoverflow
Solution 7 - JavascriptThomasView Answer on Stackoverflow
Solution 8 - JavascriptMaqsud ErjonovView Answer on Stackoverflow
Solution 9 - JavascriptYetti99View Answer on Stackoverflow