5

I would like to protect my API with CORS. I want my API to have call access only from the selected domain.

I am using node.js and express, so I add to my project: https://github.com/expressjs/cors

And example code:

var express = require('express')
var cors = require('cors')
var app = express()

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200
}

app.get('/test', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'})
})

But if I make a request via POSTMAN from localhost, I still get a response from this routing. This should be blocked and only work for requests from one domain (example.com).

I tried before:

router.get('/test', cors(corsOptions), function(req, res, next) {
  console.log(corsOptions);
  res.header("Access-Control-Allow-Origin", "http://www.example.com);
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  res.status(200).send({ work: true });
});

But this also lets my requests from POSTMAN...

I would like to have an API that can be referenced only if it comes to my example.com page and from there are requests sent by JavaScript.

fupuzo
  • 63
  • 1
  • 3
  • I think you've misunderstood how CORS works. It is enforced by the browser instead of the server. For more info look at the answer [here](https://stackoverflow.com/questions/10636611/how-does-access-control-allow-origin-header-work) – Aman B Oct 06 '18 at 16:11

1 Answers1

12

CORs only works from browsers so it will not have any effect on a request made outside a browser like from Postman. It is a technology that requires the client itself to implement the CORs protection.

There is no way to keep POSTMAN or any other programmatic access from using your API unless you implement some sort of authentication or time-based tokens. This is the nature of web-based APIs. If they can be used in your web pages, then anyone else can use them programmatically too.

The purpose of CORs is to keep other web pages from using your API from their own web page Javascript. That's ALL it protects. In fact, if another web site wants to access your API from their server and then put results into their own web pages, they can do that - CORs does not restrict server or programmatic access outside a browser at all.

For further discussion of the general topic of protecting an API, see these references:

Securing Express API

How to publish jQuery code accessing a REST api, but have it secured from unauthorized use

Setup API that only your webserver can see it

jQuery ajax security

jfriend00
  • 683,504
  • 96
  • 985
  • 979