I'm using anti-CSRF tokens on all my forms to prevent CSRF attacks. Also, the tokens are being saved in the $_COOKIE variable to validate against the value I get from the form. I'm resetting the token each time a form is loaded.
But there are a few forms that are using $.post, i.e. AJAX to submit and getting a JSON response.
The $_COOKIE variable is not set because of AJAX being used.
Is there a workaround or am I doing something wrong?
EDIT: Adding client-side and server-side code sample
Client-side:
<?php
$tokenVal = md5(uniqid(mt_rand(), true));
setcookie ("token", $tokenVal);
?>
<form action="target.php" method="post" name="abc">
<input type="text" name="city" id="city" value="abc" size="25" maxlength="10">
<input type="hidden" name="csrf" value="<?php echo $tokenVal; ?>">
<a class="cssButton buttonColor right" id="billToSubmit">Save</a>
</form>
Server-side:
if($_POST['csrf'] == $_COOKIE['token']) {
//process further
} else {
die("Invalid form source")
}
The form is being submitted using $.post. The problem I'm facing is that $_POST['csrf'] is never equal to $_COOKIE['token']!
$.post
?