Secure ajax GET / POST request to server

Suppose I am working with some kind of API and my server.php file is handling the connection to the API service. on my client side i use an AJAX call like this:

$http({
         url : 'server/server.php',
         method : 'GET',
         data : { getContent : true }
     });

      

in my server.php I am handling it like this:

if(isset($_GET['getContent'])){
    $content = get_content();
}

function get_content(){...}

      

I'm just wondering what is stopping someone from sending an AJAX call with the same getContent parameter and getting all my data? how can I secure it and make sure that only calls from my application will return the appropriate data?

Thank you!

+3


source to share


3 answers


I think you are worried about CSRF attacks. Read more about this here: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet



One of the most commonly used options for securing your request would be: - Create a token and send it with a session request. This token can be identified by your WebServer as coming from a specific client for a specific session

+5


source


I'm just wondering what is stopping anyone from sending an AJAX call with the same getContent parameter and getting all my data?

Nothing. This URL is public, so anyone can request it.

how can I secure it and ensure that only calls from my application return the appropriate data?

You can pass additional data (like some hashed value) that is checked on the server side.



$http({
     url : 'server/server.php',
     method : 'GET',
     data : { getContent : true, hash : '0800fc577294c34e0b28ad2839435945' }
 });

      

and

if(isset($_GET['getContent']))
{
    if(isset($_GET['hash']) && validateHash($_GET['hash']))
    {
        $content = get_content();
    }
}

function get_content(){...}

      

+2


source


I'm just wondering what is stopping anyone from sending an AJAX call with the same getContent parameter and getting all my data?

Likewise, you are protecting data in any other request (for example, with user authentication). There is nothing special about Ajax about HTTP in relation to the server.

how can I secure it and ensure that only calls from my application return the appropriate data?

You can not. The user can always check what their browser is requesting on the server and replicate it.

Typically, people authenticate users, not applications.

+2


source







All Articles