Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.
An example of a cross-origin request: The frontend JavaScript code for a web application served from http://domain-a.com
uses XMLHttpRequest
to make a request for http://api.domain-b.com/data.json
.
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest
and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request HTTP resources from the same origin the application was loaded from, unless the response from the other origin includes the right CORS headers.
But there are several browser plugins which bypass this same-origin policy. Those plugins can be used by hackers to attack CORS-protected websites.
There is a technology to prevent this kind of attack in Node.js projects. Node.js projects normally use cors
npm package to control CORS. We can use configuration of this package to prevent CORS attacks.
if (!origin) return cb(null, true)
origin = origin.replace('http://', '').replace('https://', '')
if (!whitelist.has(origin)) {
return cb(new Error(`origin "${origin}" is not allowed access.`))
}
return cb(null, true)
If origin is not allowed, Javascript error objects is returned. So in the browser-side, CORS-protect is bypassed by CORS extension but response will be 500 instead of 200.