Reputation: 529
I have been asked to make sure that a new express server that I've set up enforces against Cross Origin Resource Sharing (CORS) unless the request is coming from a particular URL.
I have found the official express CORS middleware here: https://github.com/expressjs/cors
If I wanted to ENABLE CORS for all requests then I just need to add app.use(cors())
.
If I want to only allow specified urls then I can pass them in as so:
var corsOptions = {
origin: 'http://example.com',
optionsSuccessStatus: 200
}
app.use(cors(corsOptions))
Correct?
What if I wanted to prevent all origins/URLS from accessing resources on my server?
Is this just the default behaviour of Express?
And if I skipped all this above code, then my server would be protected against all requests?
How am I able to use postman for testing server requests if I haven't enabled CORS using the CORS middleware?
Thanks!
Upvotes: 12
Views: 24927
Reputation: 1482
CORS only comes into play in browsers, only when a webpage from a different domain tries to access your resource. You can mannually check the origin header in the ctx (without using any prebuilt middleware)
const origin = ctx.get('origin');
//check if you want to allow this origin
//if you want to allow it,
ctx.set('Access-Control-Allow-Origin', origin);
//else do not set the header or set it something else
ctx.set('Access-Control-Allow-Origin', 'blahblah.com');
The browser will first send OPTIONS request to server to see if it allows the current origin, if not the browser does not continue to make the original request. If you look into the source for https://github.com/expressjs/cors, this is roughly what it does.
If you do not put these headers in response, the browser will falback to the same origin policy.
Upvotes: 4
Reputation: 35827
If you don't enable the CORS middleware, your server responses will not contain CORS headers, and browsers will fall back to the standard same-origin policy (i.e. only scripts on the same protocol, domain and port can access it).
Note that none of this is enforced on the server side, though - CORS simply provides information to the browser to allow it to make decisions, and there's nothing stopping a browser implementation from simply ignoring the CORS headers or the same-origin policy. For example, HTTP clients like Postman will usually disregard CORS entirely, as it's not relevant to them.
Upvotes: 15