Monday, June 14, 2010

CakePHP, restrict Ajax access to some functions

I am recently writing a system using CakePHP, with Ajax requests from another page outside the CakePHP installation.

The purpose is to make it difficult for would be hacker to retrieve information that I wanted to hide beneath the hook, while exposing to granted parties, including of course the web server itself.

Examples found online are largely into 2 categories,

a. Blanket security, i.e. access to protected areas requires password, which is good if human users are interacting with the system. But it adds complexity for ajax to do a few requests, atleast 2, one to authenticate, and the other to request data.

b. Check referrer URL to determine if requests is coming from itself, else show error message.

I am minimalist by nature, and will find ways to squeeze performance to the last drop. This is certainly not ideal.

Instead, I have put up a little piece of code to decide if the requester, be it ajax, or human, is allowed by checking their IPs. Ajax requests can only be done on local, ie. any other requests will have to route thru the usual user login path.

Below is the sample which you can insert into any function you wish to protect, that gives you flexibility on how much information is allowed to expose.

function ajaxview($id = null) {
$allowedIps = array('localhost');
if(!in_array($_SERVER['HTTP_HOST'],$allowedIps)) {
$this->Session->setFlash('Sorry, you are not allowed to access this area');
$this->layout = 'ajax';
$this->Registrant->recursive = 0;
$this->set('registrant', $this->Registrant->read(null, $id));

Simple, right?

No comments:

Post a Comment