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.
As already stated,
HTTP_REFERRERandREMOTE_ADDRcould 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
.htaccessand.htpasswdfiles, 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:password@example.comSo 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.