Tag Archive for 'ajax'

let the Web browser “remember” HTTP authentication credentials using AJAX – the correct way vs. the wrong way

Under nor­mally cir­cum­stances, if you request an HTTP pro­tected resource with your Web browser, the server would return 401 Unau­tho­rized and an popup would appear to ask you for the cor­rect credentials:

That doesn’t look too Web 2.0-ish. Cur­rently there is way to work around this using an AJAX request first (there’s an arti­cle that dis­cusses the spe­cific tech­nique used). That way, the browser would “remember” the Autho­riza­tion header used in the pre­vi­ous AJAX request, so when the user requests another pro­tected resource in the same domain, the browser would also try to include the pre­vi­ously used Autho­riza­tion header.

How­ever, I couldn’t get it to work.

It turns out that the dif­fer­ence between my approach and the approach used in the arti­cle 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 );

Unbe­known to me was the fact that the 4th and 5th para­me­ter of XMLHttpRequest.open() could be used to spec­ify the user­name and pass­word for the request.

Appar­ently, the browser doesn’t remem­ber the cre­den­tials 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 remem­ber the cre­den­tials no matter what I tried – it would still pop up an autho­riza­tion box when the user request a pro­tected resource.