Home > Articles > Programming > Java

  • Print
  • + Share This
From the author of

Verifying the AJAX Request

Now that we’re saving the password as a cookie from our index page, we’ll need to verify it on the server side when the AJAX requests are made. To do this, we’ll create a file called xmlServiceConnector.php, which we’re already requesting in our client-side PHP file. This file will contain the following code:

<?php

require_once("classes/PasswordManager.class.php");
$pwManager = PasswordManager::getInstance();

header("Content-Type: application/xml; charset=UTF-8");
echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\" ?>\n";

if( $pwManager->verifyPassword() )
{
    echo "<response>The request was successful!</response>";
}
else
{
    echo "<response>The request was not successful.</response>";
}

?>

This file first imports and gets an instance of the PasswordManager. It then includes a header that specifies the Content-Type of the file as XML, so that the response on the client side is valid XML. An XML declaration is also added to the page because it’s necessary to create a valid XML structure.

With this code in place, we can verify the password that was set in the page that should now be making the AJAX request. If the cookie password doesn’t exist, we know that the request is coming from an invalid location, and we don’t return any useful data. By calling the verifyPassword method in the PasswordManager, we can determine whether the password was previously set. Based on the Boolean, we’ll return the appropriate response to the requesting object. The verifyPassword method should be added to the PasswordManager, and should contain the following code:

public function verifyPassword()
{
    if($_COOKIE["uid"] == md5($this->pass))
    {
       return true;
    }
    else
    {
       return false;
    }
}

This method simply looks for the cookie named uid and checks whether it’s equal to an MD5-encrypted version of the $pass property. This step ensures that the cookie exists and that the cookie was created by using our unique password. In this example, we’re simply returning an XML node as a response, but this is the location where we would connect to other PHP files that would in turn connect to the database.

To test the reliability of this security model, try to make a request directly into a browser that doesn’t already have the cookie set:

http://www.krishadlock.com/clients/informit/secureajax/xmlServiceConnector.php

Without your first accessing the application that’s setting the unique cookie, all requests will be rejected.

  • + Share This
  • 🔖 Save To Your Account