Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
687 views
in Technique[技术] by (71.8m points)

ajax - How can I restrict access to some PHP pages only from pages within my website?

I have in my website a PHP page which retrieves data from my database to be presented in my website. This page is called via AJAX. How can I restrict the access to it only from pages within my website so users who wants to abuse it and get this data not from the website (e.g. posting HTTP request from their server) itself won't be able to do so ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is what I do,

  1. On your website, create a secret string. I use the HMAC($_SERVER['REMOTE_ADDR'], key).
  2. Write the secret in a Javascript var.
  3. On the AJAX call, pass this string as a parameter.
  4. 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=...&timestamp=...

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...