How to ensure access to my web service from my code only?

前端 未结 9 1921
天命终不由人
天命终不由人 2020-12-17 22:32

I am writing a very simple web service for my iPhone app. Let\'s say this is a http page that returns a random number at http://mysite/getRand. How do I ensure that this pag

9条回答
  •  北海茫月
    2020-12-17 23:19

    As some of the answers have stated, closing your web service off to everyone else will be a major hassle. The best you can hope for is to make it easier for the hackers to use another web service, than to use yours...

    Another suggestion to do this, is to generate random numbers from a random seed on both the server and the client. The server would need to track where in the sequence of random numbers all of the clients are, and match that number to the one sent by the client.

    The client would also have to register to be given access to the server. This would also serve as a authentication mechanism.

    So:

    //Client code:
    $sequence = file_get_contents('sequence.txt');
    $seed = file_get_contents('seed.txt');
    $sequence++;
    
    //Generate the $sequence-th random number
    srand($seed);
    for ($i = 0; $i <= $sequence; $i++) {
        $num = rand();
    }
    //custom fetch function
    get_info($main_url . '?num=' . $num . '&id' = $my_id);
    

    This will generate a request similiar to this:

    http://webservice.com/get_info.php?num=3489347&id=3

    //Server Code: (I'm used to PHP)
    
    //Get the ID and the random number
    $id = (int)$_REQUEST['id'];
    $rand = (int)$_REQUEST['num'];
    $stmt = $db->prepare('SELECT `sequence`, `seed` FROM `client_list` WHERE `id` = :id');
    if ($stmt->execute(array(':id' => $id)) {
        list($sequence, $seed) = $stmt->fetch(PDO::FETCH_ASSOC);
    }
    $sequence++;
    
    //Generate the $sequence-th random number
    srand($seed);
    for ($i = 0; $i <= $sequence; $i++) {
        $num = rand();
    }
    if ($num == $rand) {
        //Allow Access
    } else {
        //Deny Access
    }
    

    By using a a different seed for each client, you ensure that hackers can't predict a random number by tracking previous numbers used.

提交回复
热议问题