Reputation: 382796
We have REST API that we want only our domain has access to and that spoofed requests are not sent. To do so, the only thing coming in my mind was checking the referrer $_SERVER['HTTP_REFERER']
. However the docs say that:
The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.
So let's say our main API requests/gate file is:
www.example.com/api/gate.php
How do I make it secure so that only requests from own domain are served and all other disregarded? I have read a little about http authentication and setting up private keys or secret but I am looking for a simple way so only our own domain can send requests to that file.
Upvotes: 3
Views: 3539
Reputation: 11447
Wouldn't a simple .htaccess in the public_html/api subfolder that allows access to localhost only do the trick?
order deny,allow
deny from all
allow from 127.0.0.1
or, if you only ever access the gate.php file and need other files in the folder to be accessible you could just target the one file
<files "gate.php">
order deny,allow
deny from all
allow from 127.0.0.1
</files>
Upvotes: 2
Reputation: 5106
As already stated, HTTP_REFERRER
and REMOTE_ADDR
could be potentially spoofed, and thus can't be trusted to implement said functionality. Also keep in mind that in a shared hosting context other accounts in the same server also have the same IP.
A quick solution could be to use Basic Authentication to authenticate the requests to the API. This won't filter by IP or referrer URL/IP but will ensure that requests come from a trusted source.
In a Apache environment setting up Basic Authentication is as easy as creating the .htaccess
and .htpasswd
files, and putting them in the root directory of your API.
You can create both files using the following generators:
.htaccess generator
.htpasswd generator
After setting up Basic Authentication, authenticating your requests in PHP is as easy as accessing your API in the following fashion:
username:[email protected]
So no extra code needs to be developed to set any headers to authenticate your requests. Anyone accessing the URL will be prompted for credentials, denying access if authentication fails.
Upvotes: 5
Reputation: 55962
I believe that the HTTP_REFERRER
and REMOTE_ADDR
are just sent in the request headers, meaning they can be spoofed. If your site is on the internet and you want to restrict access to it, this is not the way to do it. Full authentication is necessary, using credentials.
If you don't want to set up authentication or keys, you could just host it on your companies LAN.
Upvotes: 2
Reputation: 4694
There is also $_SERVER['REMOTE_ADDR'] which would be less likely to be spoofed.
Is it safe to trust $_SERVER['REMOTE_ADDR']?
Upvotes: 0