Protecting a route used by a single domain

Asked

Viewed 416 times

3

I have an Laravel application hosted in a subdomain and need to allow your API (which has a single POST route) to be used solely by the application hosted in the main domain.

What is the simplest way to protect this route? I thought about using JWT, but since route usage is automated, I had expired token issues. I also thought about creating a middleware to check the user-agent, but it can be modified.

  • Access-Control-Allow-Origin: domain.com

1 answer

2

CSRF protection:

If you’re worried about someone reading the content, there are two "distinct":

Get your /json.json on the client’s side, via Javascript/Ajax.

Get your /json.json on the "server"/"client" side, via cURL/Wget/Webviewer (and "custom browsers").

The first situation is easier and in fact "there is something to do" to prevent:


Add the header of Access-Control-Allow-Origin, strict to your website.

(Optional) Add the Access-Control-Allow-Headers, limit headers (eg. X-CRSF-TOKEN) that can be sent.

(Optional) Add the Access-Control-Allow-Methods, limit the accepted methods (ex. GET) so only this method will be accepted.

So you can use:

header('Access-Control-Allow-Origin: http://www.dominio.com http://m.dominio.com');
header('Access-Control-Allow-Methods: GET');

I recommend seeing this answer.


Add a CSRF Token. The CSRF Token must only be valid for a single session. (Recommended) The CSRF Token must be valid for a single IP. (Optional) The CSRF Token should expose after a single use. (Optional) The CSRF Token must be unique for each URL or each tracking.

You can read this answer


Measures that are inefficient but can help:

Check the Referrer/Origin, are easily forged. The second situation is impossible to be corrected, literally there is no way to prevent this, everything listed above is not enough to prevent the use of cURL/Wget.

Create a Rate-Limit, a limit on how many times the page can be accessed per second per IP (or range of IPv6) is relatively efficient as it will require the use of several proxies if you want to get the content constantly, but remember the CGNAT in the IPv4. Block access via TOR and public proxies.


Much less efficient measures, but they can help:

Create a "challenge" in Javascript, such as jjencode, Cloudflare uses this.


Other answers that may complement:

Server Side Only Rest Api

Oauth authentications for REST Apis

  • thanks for the great answer. What I’m also looking for is to prevent the route from being used outside the domain.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.