How to prevent cross-domain ajax requests?

后端 未结 6 1216
闹比i
闹比i 2020-12-05 16:43

How can I detect if my php script is being called from another domain and the other domain is making illegal use of my script? Is there a way to prevent this too?

<

6条回答
  •  日久生厌
    2020-12-05 17:26

    for user3491125's answer, you could try encrypting the session token. I have one encryption function that can add a unique key based on a users port 80 IP. it's Not foolproof, but it does make it more difficult for hackers.

    function encryptString($string, $action, $baseIP = 'false', $extraKey = ''){
        global $flag;
    
        $encryptedIP = '';
    
        if($baseIP){
            $encryptedIP = encryptString(strip_tags(htmlentities($_SERVER['REMOTE_ADDR'])), 'encrypt', false);
        }
    
        $output = false;
    
        $encrypt_method = "AES-256-CBC";
        $secret_key = $flag['encrypt-key'].$encryptedIP.'-'.$extraKey;
        $secret_iv = $flag['encrypt-secret'].$encryptedIP.'-'.$extraKey;
    
        $key = hash('sha256', $secret_key);
        $iv = substr(hash('sha256', $secret_iv), 0, 16);
    
        $output;
    
        if($action == 'encrypt'){
            $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
            $output = base64_encode($output);
            $output = str_replace('=', '[equal]', $output);
        }else if($action == 'decrypt'){
            $setString = str_replace('[equal]', '=', $string);
            $output = openssl_decrypt(base64_decode($setString), $encrypt_method, $key, 0, $iv);
        }
    
        return $output;
    }
    

提交回复
热议问题