AJAX - The Complete Reference

(avery) #1

PART II


Chapter 7: Security Concerns 305


Hopefully, such error pages will have been replaced with more pleasing and data
sanitized pages.
Recall from Chapter 3 that with Ajax, the XMLHttpRequest object can pass the open
method a username and password value that will be used to answer an HTTP challenge
issued.

xhr.open(request.method, request.url, request.async, request.username,
request.password);

We extend the library now to take those values, as shown by this small code snippet:

var url = "protected/myprotectedpage.php";
var options = { method: "GET",
username : "baltar",
password : traitor46,
onSuccess : showResponse,
onFail : showFail};
AjaxTCR.comm.sendRequest(url,options);

You might then decide to build your own custom login form as shown in the example
at http://ajaxref.com/ch7/authentication.html. In this case, when entering the correct
username and password, the 401 challenge will be responded to correctly and the user will
be granted access to the resource with the browser automatically sending the appropriate
Authorization header on any subsequent requests. However, if the credentials are not
correct, as stated before, the user should get three tries before receiving an error message
saying that they are not authorized.
Unfortunately, the behavior of the XHR and browser varies in the case of authentication
failure. In some browsers, the XHR will send the same credentials three times and then the
XHR will finish with a readyState of 4 and a status of 401. However, in many browsers
the built-in HTTP login dialog will be issued upon failure and the normal XHR request
cycle may appear to be interrupted. This certainly could be very confusing for users, so try
to avoid this at all costs. You can see this unfortunate situation in Figure 7-5, and you can try
it for yourself using the example to see what your particular browser does.
Possibly if protecting private resources is approached a bit differently, we might have
better luck in making them work with an XHR. In the example at http://ajaxref.com/ch7/
authenticationbasic.html a PHP page is called and found outside of the protected area
which will do the authentication. By doing it this way, it is possible to control what gets
returned to the client and avoid having the default browser challenge show.
The code is quite simple so here’s a quick walk-through. First, define the username and
password you are attempting to match. Obviously, this could be stored in a database or text
file, but in the example presented here, hard-coded credentials are used:

$user = 'AjaxBasic';
$password = 'basic';
if (!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW']))
{
header('WWW-Authenticate: Basic realm="Secure Basic"');
header('HTTP/1.1 401 Unauthorized');
}
elseif ( isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] == $user
Free download pdf