yurikilian
yurikilian

Reputation: 33

How to protect ajax methods called via jquery?

I have a datagrid table in a user session (users visualizations by admin).

To initialize the datagrid I need to set the url data with an array with the items that should be in the table.

To do this, I must have an action allowed to show these data (Codeigniter mvc).

How can I protect my action to only allow access by users of my app via the jQuery.ajax() method?

For example, I'm already logged into my session and access a view with datagrid that uses this function to get the data and set it on a table:

  $('#content').WATable(
  {
    url: '/api/showusers'
  }).data('WATable');

Thank you!

Upvotes: 0

Views: 267

Answers (1)

Lea
Lea

Reputation: 602

In app/config/constants.php

define('IS_AJAX', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest');

Then in showusers()

public function showusers() {
    if(!IS_AJAX) { 
        show_404()
    }

    // continue with processing
}

I use this Everywhere! If you're in a user-only area, codeigniter will handle the user authentication and make sure the action is being accessed only by ajax.

Upvotes: 1

Related Questions