In cases where cross-domain scripting is desired, CORS allows web developers to work around the same-origin policy. CORS adds HTTP headers which instruct web browsers on how to use and manage cross-domain content. The browser then allows or denies access to the content based on its security configuration.
How CORS Works
When a browser executes a script that references a resource on another domain, it requests the content directly from the second domain. The second domain determines whether or not to serve the content by validating the first domain, which is included as part of the request. The second domain then returns either the content or an error message back to the browser, bypassing the first domain entirely.
Step-by-step, here’s how CORS works:
- The user’s browser creates a connection to the second domain, adding an
OriginHTTP header to the request which contains the first domain.
- The second domain replies with an
Access-Control-Allow-OriginHTTP header which lists the domains allowed to make CORS requests. A wildcard (“*”) allows all domains to make requests.
- If the first domain is allowed to make the request, the second domain responds with the requested content.
Access-Control-Allow-Origin header is defined in the second domain’s server configuration. If the header doesn’t contain wildcards and the first domain isn’t explicitly included, the browser displays an error message.
Example of CORS
CORS is an essential feature of online storage services such as Amazon S3. Service providers configure S3 to allow CORS requests from their website’s domain. When a user accesses the website and runs the script, their browser makes a request to S3. Since S3 is configured to allow the domain, the request is completed and the content is delivered to the browser.
More complicated cross-domain requests use preflighting to validate a request before the request is actually performed. Preflighted requests include custom HTTP headers which help the server determine whether or not a request is valid. Preflighted requests help service providers better protect sensitive information from users who might abuse CORS requests.
Hackers are always looking for ways to undermine the security of the web. To this day, cross-site scripting (XSS) is one of the most popular ways of bypassing the same origin policy, and accounted for 84% of all security vulnerabilities not long ago. The great thing about CORS is that it gives web services the freedom to interconnect with other web services without making their users vulnerable to attack.