James John – Software Engineer

Securing Your AJAX Call-up Pages – Advanced

AJAX is cool, makes it able for you to do multiple things on a page without reloading and creating extra pages but how secure can it be? You may wish to run some actions on an AJAX page and without security even GoogleBot in the act of crawling your page executes the action. AJAX requests a page with XMLHttpRequest so there is already an existing simple procedure of securing your page, below I wrote the function:

<?php
function is_ajax() {
	if ( empty ( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) || isset ( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] !== 'XMLHttpRequest') { 
		return false;
	}
	else
		return true;
}

Using the above function, a page returns false if hit with browser but running this:

curl --header 'X-Requested-With: XMLHttpRequest' http://site.com/yourtestfile.php

returns true instantly! 😀 So I can still execute what I want to execute to any page.

THEN WHAT’S NEW?

Not actually new, but it’s a cool way of securing your AJAX I thought of. Using Session IDs, this IDs are already hashed with MD5 but we are gonna still encrypt it more with stronger one, and the above function I recode it with

<?php
// --- Add this line to your config and include to all page
if( !session_id() ) {
	session_start();
	$id = hash( 'sha256', session_id() );
	define( 'AJAX_TOKEN', $id );
}
//--ends

function is_ajax( $token ) {
	if ( empty ( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) || isset ( $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] ) && $_SERVER[ 'HTTP_X_REQUESTED_WITH' ] !== 'XMLHttpRequest') { 
		return false;
	}
	else {
		if( defined( 'AJAX_TOKEN' ) && AJAX_TOKEN == $token )
			return true;
		else
			return false;
	}
}

Because no normal browser can access with XMLHttpRequest, using tools like cURL or wget won’t store cookies…they are text browsers. So each visit creates a new Session ID for them and messes up everything for them, so your AJAX URLs should not look like http://testsite.com/ajaxlink.php?token=2i4j2jk..use the token query and pass as the function argument to check if it’s truly AJAX.

James John

Software Engineer