CORS
What is cors
Stands for Cross Origin Resource Sharing
.
Used by browsers to control how resources
are requested from a different origin
than the one the browser is currently on.
CORS does NOT affect mobile applications, desktop applications, or server-to-server requests.
Restricts how a document
or script
loaded by one origin
can interact with a resource from another origin
.
- It was created to isolate malicious documents, reducing attack vectors.
How CORS Works
Steps:
- The
browser
adds an origin header to the request with information about thecurrent origin
's protocol, host, and port. - The
server
(third party) checks the currentorigin header
and responds with the requested data and anAccess-Control-Allow-Origin
header. - The
browser
sees the access control request headers and shares the returned data with theclient application
.
Prevents CSRF
Cross-site request forgery (CSRF
) sends fake client requests from the victim's browser to another application.
For example, the victim logged into their bank's application. Then they were tricked into loading an external website on a new browser tab. The external website then used the victim's cookie credentials and relayed data to the bank application while pretending to be the victim. Unauthorized users then had unintended access to the bank application.
Today, browsers enforce that clients can only send requests to a resource with the same origin as the client's URL. The protocol, port, and hostname of the client's URL should all match the server it requests.
How to Use cors
By default, CORS
is disabled and prevents all other origins
from loading document or script.
CORS
lifts the restriction to allow access for other origins.
Example: CORS
should be enabled for the localhost
when in local development, making a request to a server instance.
const cors = require('cors'); const express = require('express'); const app = express(); // Enable CORS for a single route app.get('/public', cors(), (req, res) => { res.json({ message: 'This is a public route' }); }); // Enable CORS with specific settings for another route app.post('/private', cors({ origin: 'https://trusted-origin.com' }), (req, res) => { res.json({ message: 'This is a private route' }); }); // more complex configuration as a middleware app.use(cors({ origin: 'https://yourwebsite.com', methods: ['GET'], allowedHeaders: ['Content-Type', 'Authorization'], maxAge: 600 }));
What it is not
CORS
doesn't work on server requests
Server environments do NOT enforce CORS
so they can bypass any CORS
restrictions.
CORS
is a feature on browser.
curl
can easily spoof CORS
by declaring origin url:
curl -H "Origin: example.com" www.yourweb.com"
Hence, CORS
is NOT a valid mechanism of protecting against server-to-server
requests.