Rookie
Rookie

Reputation: 193

Plesk/PHP Accept Requests Only From Your Domain

I'm currently developing a forum-like website for the purpose of learning developing web applications and application security. Some part of the website is protected by credentials.

But there is a .php script that returns latest news. And my news.php (through javascript and jquery ajax) makes a request to return_news.php to get a json file of information about latest news. And at this point a problem arises. Anyone can send a request to return_news.php and display my data on their website. I want to make it so that only the files on my host can make requests to my endpoints or make data accessible only through my domain https://www.example.com and reject any request that comes from other origins.

What I've done:

I did some research on the internet. Read some articles about CORS and .htaccess file. But my host is on a cloud server and I don't think I have access to it. And I couldn't find a way of checking the current configurations for my hosting. The issue seems to be related to CORS but I couldn't find a detailed explanation on how to achieve my goal.

Summary: How can I configure my website so that the content is only available through my domain (e.g. https://www.example.com), my api responds to requests that originate from only my domain and my content can't be obtained by just a get request and displayed in another website?

Upvotes: 0

Views: 777

Answers (1)

GramThanos
GramThanos

Reputation: 3622

By default browsers block the response of ajax requests to cross domains, for security reasons. This means that by default, any website from an other domain that creates an ajax request to your return_news.php will not get the response (although the request will be made).

There is also a HTTP header for specifying if you want to allow CORS or not. Thus in your case, just to be sure, you can set it at the top of your return_news.php file

header("Access-Control-Allow-Origin: https://www.example.com");

This instructs browsers to return the response only then the ajax comes from a page under the www.example.com domain.

You may check it by visiting any other domain page and test it on the javascript console, then check the network tab for more info.

fetch('https://www.example.com/return_news.php').then(function(response) {console.log(response);})

Upvotes: 1

Related Questions