Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sure that only a specific domain can query from your REST api?

Tags:

I have an app that has a REST api. I want it so that the only requests that can be made to the REST api are ones originating from the app itself. How can I do that? I am using a node.js+express server too.

EDIT: the app is fully a public web app.

like image 529
omega Avatar asked Jan 11 '17 16:01

omega


People also ask

How do I restrict an API call?

If you want to restrict usage and make it inconvenient for abusers to call your API, you can issue a token on page load (CSRF token) and require that token to be present in the request to the API - that way the API will be callable from a browser that initiated a page load.

How do I restrict API access from postman?

You will not be able to disallow your API for any particular client. You can reject the request based on the source IP or port, the headers including user agent, API keys or other credentials, but if your API can be accessed at all, then it can be accessed by postman or any other client using the same data.

How do I handle multiple API requests?

If you need to make multiple API requests, you can send these API requests concurrently instead of sending them one by one. Sometimes, we need to make multiple API calls at once. For example, let's say we have an array, and we want to make an API request for each element of that array.


1 Answers

Simply define the header in your request, what this does is, it allows requests only from a certain domain, and instantly rejects any other domain.

response.set('Access-Control-Allow-Origin', 'domain.tld'); 

EDIT: IF you're really keen against web scraping stuff, you could make a function to double check client's origin.

function checkOrigin (origin) {    if (origin === "your.domain.tld") {      return true;    } else {      return false;    } } /* Handling it in response */ if (checkOrigin(response.headers.origin)) {   // Let client get the thing from API } else {   response.write("Send them error that they're not allowed to use the API");   response.end(); } 

Above example should work for the default HTTP/HTTPS module, and should also work for Express, if I'm not mistaken.

EDIT 2: To back my claim up that it should also work for Express, I found this quotation at their documentation;

The req (request) and res (response) are the exact same objects that Node provides, so you can invoke req.pipe(), req.on('data', callback), and anything else you would do without Express involved.

like image 122
Cernodile Avatar answered Oct 14 '22 17:10

Cernodile