Yomesh Yomesh - 3 months ago 15x
Ajax Question

Stop Malicious POST requests

I have an AJAX function that makes call to a page on my website.

$(document).on('click', thisIdentity, function() {
var trigger = $(this);
var items = trigger.attr('data-values').split('_');
type: "POST",
url: "/mod/mypage.php",
data : { pid : item[0], uid : item[1] },
dataType: "json",
success: function(data) {
if(data.job == 1) {
// do something

Now this works fine and do as intended. However, if I use any third-party app like POSTMAN and make a POST request to www.xyz.com/mod/mypage.php with parameters pid : 1 and uid : 2. It still goes through and make changes to my database.

Is there anyway to check that request is generated from my
domain/server only?

How to stop such POST requests outside from my domain?

One thing I thought was to generate a token and set in SESSION before this request and check in mypage.php that if token is set or not. Is this a feasible way?


This is exactly what a CSRF token is for. Users must navigate to the page first, which generates a token to submit, ergo without navigating to the page will render any POST requests invalid.

However, trying to stop someone from POST'ing a request to your endpoint from a utility like POSTman is an exercise in futility. You must authenticate every request to the endpoint, in this case just check the photo id is owned by the submitting client.

OWASP provides a decent description of what a CSRF is:

Cross-Site Request Forgery (CSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated. CSRF attacks specifically target state-changing requests, not theft of data, since the attacker has no way to see the response to the forged request.

Example validation flow



// Establish DB connection, validate

$_SESSION['id'] = $db->getUserId();
$_SESSION['admin'] = $db->getAdminStatus();



if (!$db->isPhotoOwner($_POST['pid'])) {

// Delete photo flow



if (!$_SESSION['admin']) {
    die("Not admin.");

// Do admin action or whatever