I would like to create a new token for each request and would like to us the following template-
<script>
var current_token=<?php echo $_SESSION['csrf_token']; ?>
$.ajax({
type: "POST",
url:"script.php",
data: {'token':current_token},
success: function(data) {
var result=JSON.parse(data);
current_token=result.token;
},
error:function(error){
console.log(error);
}
});
</script>
here is script.php
<?php
if($_POST['current_token']==$_SESSION['csrf_token']){
//do your thing
$token="new token" //generate new token here
$_SESSION['token']=$token;
$response['token']=$token;
$out=json_encode($response);
die ($out);
}else{
//request failed - handle as error and ask to re-login or whatever
}
?>
explanation-
- You send your AJAX, validate the session token and post token
- If successful, generate new token
- Update the token in $_SESSION['token'] and also send the new token back
- Use the success function retrieve the token and update in your JavaScript
It this a good idea? Or does this create a new vulnerability like an XSS spoof ?