Private REST API

We have a REST API that we only want our domain to have access and these fake requests are not being sent. For this, the only thing that came to my mind was the referee check $_SERVER['HTTP_REFERER']

. However, the docs say that :

The address of the page (if any) that linked the user agent to the current page. This is set by the user agent. Not all user agents will install this, and some provide the ability to modify the HTTP_REFERER as a feature. In short, it cannot be trusted.

So let's say our main API requests / gatefiles file:

www.example.com/api/gate.php

      

How to make it secure so that only requests from your own domain are served and all others are ignored. I did a bit of getting around with http authentication and setting up secret keys or secret, but I'm looking for an easy way so only our own domain can send requests to this file. Thanks to

+3


source to share


4 answers


As already stated, HTTP_REFERRER

both REMOTE_ADDR

can be potentially tampered with and therefore cannot be trusted to implement the specified functionality. Also keep in mind that in shared hosting mode, other accounts on the same server also have the same IP address.

A quick solution might be to use Basic Authentication to authenticate API requests. This will not filter by IP or referrer / IP url, but will ensure the requests are coming from a trusted source.

In Apache, setting up Basic Authentication is as easy as creating the .htaccess

and files .htpasswd

and placing them in the root directory of your API.

You can create two files with the following generators:
. htaccess generator
. htpasswd generator



With basic authentication set up, authenticating your requests to PHP is as easy as accessing your API, like this:

username:password@example.com

This way, you don't need to develop additional code to set headers to authenticate your requests. Anyone accessing the URL will be prompted for credentials, denying access if authentication fails.

enter image description here

+5


source


I believe that HTTP_REFERRER

and are REMOTE_ADDR

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 required using credentials.



If you don't want to configure authentication or keys, you can simply host it on your local network.

+2


source


Wouldn't there be a simple .htaccess in the public_html / api subfolder that only allows localhost access is a 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 access, you can just target one file

<files "gate.php">
    order deny,allow
    deny from all
    allow from 127.0.0.1
</files>

      

+2


source


There is also $ _SERVER ['REMOTE_ADDR'], which is less likely to be tampered with.

Can you trust $ _SERVER ['REMOTE_ADDR']?

0


source







All Articles