Search code examples
javascriptphpjqueryajaxcsrf

Prevention against CSRF?


I often use AJAX to write into MYSQL database like so

$.ajax({ 
    url: "writescript.php",
    type: "POST",
    data: { data : mydata,//this could be anything
     },
    success: function (html) {
      //do something
  }
});

And the writescript.php looks like this

$data=$_POST["data"];
//and then write into database.

Now this works and everything but then anybody can view the ajax request since it's pure JS and can be viewed from the page source. Given the information about the script name and parameters, an attacker could try to call the writescript as well and write into my database or read depending on what the script does. This is obviously not good. So am I missing something here? Is AJAX not designed to be used for such stuff? Or am I using it wrong?


Solution

  • I don't think a CSRF problem is presented here. CSRF means an attacker tricking a legitimate and authenticated user into hitting a page by clicking a link or any other means, in turns doing things on behalf of them. If your application checks for the header to make sure the request is an ajax call from the browser, and do not allow cross domain ajax requests, theoretically an attacker could not perform a CSRF attack

    The problem you presented is more of an authorization problem. You are afraid that an attacker can write/read into your database, but any legitimate users should be able to do that, so naturally the solution is to add an authentication layer to fend off attackers.