Under normally circumstances, if you request an HTTP protected resource with your Web browser, the server would return 401 Unauthorized and an popup would appear to ask you for the correct credentials:
That doesn’t look too Web 2.0-ish. Currently there is way to work around this using an AJAX request first (there’s an article that discusses the specific technique used). That way, the browser would “remember” the Authorization header used in the previous AJAX request, so when the user requests another protected resource in the same domain, the browser would also try to include the previously used Authorization header.
However, I couldn’t get it to work.
It turns out that the difference between my approach and the approach used in the article above is this:
// My way (doesn't work)
var xhr = new XMLHttpRequest;
xhr.open ( 'GET', '/url/to/resource', false );
xhr.setRequestHeader ( "Authorization", "Basic " + Base64.encode ( username, password ) );
xhr.send ( null );
// The working way
var xhr = new XMLHttpRequest;
xhr.open ( 'GET', '/url/to/resource', false, username, password );
xhr.send ( null );
Unbeknown to me was the fact that the 4th and 5th parameter of XMLHttpRequest.open()
could be used to specify the username and password for the request.
Apparently, the browser doesn’t remember the credentials if I call XMLHttpRequest.setRequestHeader
directly.
Note: All these have only been tested to work with MSIE/Firefox. Opera for instance, doesn’t seem to remember the credentials no matter what I tried – it would still pop up an authorization box when the user request a protected resource.
0 Responses to “let the Web browser “remember” HTTP authentication credentials using AJAX – the correct way vs. the wrong way”