AJAX - The Complete Reference

(avery) #1

100 Part I: Core Ideas


The XMLHttpRequest object supports HTTP authentication in that it allows specification
of a username and password in the parameters passed to the open() method.

xhr.open("GET", "bankaccount.php", true, "drevil", "onemillion$");

Of course, you will need to make sure that such a request runs over SSL if you are
worried about password sniffing during the transmission. Furthermore, you wouldn’t likely
hardcode such values in a request, but rather collect this data from a user via a Web form.
Interestingly, while the open() method accepts credentials passed via parameter, those
credentials are not automatically sent to the server upon first request in all browsers. Opera
sends it this way. Internet Explorer does not and waits until the server challenges the client
for credentials with a 401 - Access Denied response code. You can see that in the
communication trace presented in Figure 3-7. Otherwise, Internet Explorer 7 acts just as you
would expect and does not throw any user prompts regardless of correctness or incorrectness
of authentication attempt. Other browsers like Opera and Firefox may not act so graceful
when authentication fails; they may present the browser’s normal challenge dialogs to the
user despite the authentication being handled by an XHR. However, in all cases, once the
authentication is verified in whatever manner, the onreadystatechange function gets
called with readyState equal to 4 as expected.
There may also be a variety of problems in browsers even with successful authentication
tries. Numerous older versions of Opera and Firefox and, in some cases, newer versions did
throw user challenges up even on successful tries, which defeats the whole purpose of using
this method. Yet in other installations and operating system combinations, they did not
exhibit such problems.

Given the inconsistency of how HTTP authentication is handled in XHRs, you are
advised to avoid it and use your own form of user credential checking. However, if for
some reason you must use it, you should thoroughly test the state of authentication support
in browsers yourself by running the code at http://ajaxref.com/ch3/authentication.html.
Free download pdf