I'm fairly new to web security. I was wondering what would be the correct way to use tokens on requests in javascript to protect again CSRF. Could someone show me a code sample? I know how to do it properly for forms with a submit button.
dataType: "text",
url: '/username.php',
data: 'username=' + $('#username').val() + '&Rand=' + (Math.random()*10000),
type: 'GET',
That's a sample code from my script. It just searches for a username and returns if it's taken or not. How would we send a token via Javascript and validate it on username.php? Thank you
If you know how to do it on forms with a submit button, it's not that different. The token generation has to be done on the server, and stored, no matter what.
Even if you are using Javascript, you are using PHP in order to output that page containing the javascript code right?
So a very quick code example may be below:
The code of the PHP file which outputs your javascript:
<?
$token = md5( mt_rand() . session_id() );
$_SESSION['token:'.$token] = true;
?>
Your javascript:
dataType: "text",
url: '/username.php',
data: 'username=' + $('#username').val() + '&token=' + '<?=$token?>',
type: 'GET',
Your username.php:
if ( $_SESSION["token:".$_POST["token"]] == true ){
exit();
} else {
unset($_SESSION["token:".$_POST["token"]]);
}
Beware, the above example has some problems, such as "the token will become renewed when you open the same page multiple times", and what not. So it is not a code ready for production usage. [UPDATE] I updated the code to resolve the "token will be renewed..." issue.
But you get the idea.
Generate the token on the server, use the token in your javascript, then evaluate it in your username.php
.
P.S. If your javascript is an external script file, just load it as a global variable on your page that loads the javascript, and use the variable in the external javascript file.