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

后端 未结 6 959
北海茫月
北海茫月 2020-12-16 05:08

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 f

6条回答
  •  庸人自扰
    2020-12-16 05:37

    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,

    
    

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

提交回复
热议问题