-1

Consider the following web application: the frontend contains a button and some sliders. When the button is pressed, a request is sent to the server along with the sliders value. The server calls a python script and generates some content according to the sliders value and the content is then displayed on the frontend.

How can I prevent other people to implement a similar application that sends requests to the same server to generate content?

firion
  • 296
  • 3
  • 12

2 Answers2

1

The solution which you are looking for is known as CSRF (Cross-Site request forgery). There are a few essential steps which you need to follow in order to prevent this

  1. Generate a unique token (something like a hash)
  2. Send this token to the frontend and use this hash in the request URL (may be in request payload or query parameter)
  3. Upon receiving the request on the server, validate the hash
  4. If the hash is valid, continue with your operation and in response generate a new hash (which will be then used in next request) and destroy the current hash (so that it can not be reused)
  5. If the hash invalid, reject the request and show some error message

Here are a few references which you might need to look:

Tejashwi Kalp Taru
  • 2,994
  • 2
  • 20
  • 35
  • Does this prevent someone to copy the frontend code and creating the same service on another website? – firion Feb 27 '19 at 14:37
  • Yes sure, given two conditions i.e., your hash/token generation and verification system should not be exposed publically and the implementation should be secure enough such that no one can guess the hash. But it may depend on how your frontend is communicating with the server? Pure API call/response based or your backend sends the HTML (view) response? – Tejashwi Kalp Taru Feb 27 '19 at 14:39
1

If your problem is another site calling your service a simple solution would be checking if the Origin header of the request received is equal your hostname and/or domain.

Like this:

<?php

// This will check the Origin header

if($_SERVER['HTTP_ORIGIN'] == "http://yoursite.com") {
    header('Access-Control-Allow-Origin: http://yoursite.com');
    // your custom logic to return the slide content
} else {
   // return a 404 error
}

A deeper explanation and complete code example can be found at:

Igor Silva
  • 46
  • 4