This is what I do,
- On your website, create a secret string. I use the HMAC($_SERVER['REMOTE_ADDR'], key).
- Write the secret in a Javascript var.
- On the AJAX call, pass this string as a parameter.
- On the AJAX server, do the hash again. If it's matches the parameter, the call is from your page.
EDIT: Code examples,
In your website, you do this,
$key = 'supersecretkey'; // This is your security, don't expose this
$nonce = rand();
$timestamp = time();
$signature = hash_hmac('sha1', $_SERVER['REMOTE_ADDR'] . $nonce . $timestamp, $key);
Print out the vars to the page,
<script type="text/javascript">
<?php
echo " var signature = '" . $signature . "';
";
echo " var nonce = '" . $nonce . "';
";
echo " var timestamp = '" . $timestamp . "';
";
?>
</script>
When you make AJAX call, pass the 3 parameters to the server,
http://example.com?signature=...&nonce=...×tamp=...
On the AJAX server, do the calculation again,
$key = 'supersecretkey'; // This is your security, don't expose this
$nonce = $_REQUEST['nonce'];
$timestamp = $_REQUEST['timestamp'];
$signature = hash_hmac('sha1', $_SERVER['REMOTE_ADDR'] . $nonce . $timestamp, $key);
if ($signature == $_REQUEST['signature'])
// the call if from my page.
You can also chech timestamp for currency and nonce for replay (need session or data store).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…