The Internet can be a dangerous place if you take a wrong turn, however, there are security features like Cross-Origin Resource Sharing (CORS) that have a key role in upholding the security and reliability of websites.
CORS allows browsers to limit how web pages from one domain can request and exchange resources, such as data, images, or scripts, with other domains. It is an important security measure, shielding us from potential threats and safeguarding user data.
In this article, we’ll see how CORS brings a secure and cooperative coexistence among diverse resource origins on the web, which contributes to making the users’ browsing experience a lot safer.
Table of Contents
What is Cross-Origin Resource Sharing (CORS)?
Cross-Origin Resource Sharing (CORS) works as an important security mechanism, determining if resource requests between different domains are allowed or not. Same-origin security policies are useful to prevent a website from initiating requests to a domain that is not the same as the one hosting the original page. CORS’s job is to determine how browsers should manage cross-origin resource requests.
When a browser initiates a request to a domain different from the present page, these headers are sent along with the HTTP request. They tell the server whether the request should be approved or rejected. The server responds with its own CORS headers specifying which entities are authorized to access the resources and which HTTP methods are not allowed.
The usage of CORS has two purposes: it stops security threats, such as unauthorized cross-origin requests, and it also streamlines the cooperation between websites. It is very important for web developers and server administrators to accurately configure CORS headers to allow for secure and seamless interactions across diverse domains, also allowing for regulated resource sharing, which is key for the development of dynamic web apps in the modern Internet.
The function of Cross-Origin Resource Sharing
As we have already explained, CORS, or Cross-Origin Resource Sharing, acts like a security system in web browsers. It manages how one website requests and receives data from another.
When a web page tries to get information from a different domain, CORS steps in to decide if it’s allowed. It works by servers specifying, in advance, which websites are permitted to access their resources through special rules in HTTP headers, such as “Access-Control-Allow-Origin.”
Think of CORS as a permission check: if the requesting website is listed, the browser lets it proceed. CORS also allows servers to set more detailed rules, like which types of requests are accepted or if custom data can be shared. This system prevents unauthorized access and enhances the security of web apps.
To make it simple, Web.dev says that “Enabling CORS lets the server tell the browser it’s permitted to use an additional origin.”
Statistics provided by BuiltWith say that a little over 2000 sites among the top 1 million use this feature.
The security of Cross-Origin Resource Sharing (CORS)
Using CORS, which lets different websites share information, can be safe if done the right way. CORS is like a security rule in web browsers that limits how websites can ask for and use data from other places. It’s necessary to turn on CORS if you have a website that needs to use resources from places that are not its server, but it’s also important to set up CORS correctly to keep things safe.
If CORS is not set up properly, it might expose the server to risks by letting in requests from places that shouldn’t have access. To make it safe, it’s important to control and limit where requests can come from and use other CORS settings.
So the short answer is yes, turning on CORS can be safe, but don’t forget to do it carefully and set it the right way to avoid any possible security issues.
What is the difference between CORS and CSP?
CORS (Cross-Origin Resource Sharing) and CSP (Content Security Policy) are different because they do different jobs for web safety. CORS helps with allowing or stopping requests for things like images or scripts between different websites in the browser. It decides how the browser should handle requests between sites to stop security problems.
On the other hand, CSP deals with lowering risks from attacks like Cross-Site Scripting (XSS). It does this by ruling from where the browser can get resources like scripts or images. CSP makes a rule that tells the browser what sources are safe and what sources are not, stopping the execution of malicious codes.
To put it simply, CORS manages requests between websites, while CSP controls from where the browser gets its resources, stopping the potential execution of harmful code. Both are important for making web applications more secure.
Cross-Origin Resource Sharing directives and examples
CORS directives are instructions from a web server to a web browser about how to handle requests from different websites. These instructions are sent through special headers in the server’s response. Here are the main Cross-Origin Resource Sharing directives, and let’s see a few examples too:
Access-Control-Allow-Origin: it says which websites are allowed to use the resource.
Examples:
Allow one specific website:
Access-Control-Allow-Origin: https://example.com
Allow any website:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: lists which actions (like GET or POST) are allowed.
Example:
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: this one lists which types of information can be sent with the request.
Example:
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: tells whether the browser can send things like cookies with the request.
Example:
Access-Control-Allow-Credentials: true
Access-Control-Expose-Headers: it lists which response headers the browser can see.
Example:
Access-Control-Expose-Headers: Content-Length, X-My-Custom-Header
Access-Control-Max-Age: determines for how long the browser can remember the permissions without asking again.
Example:
Access-Control-Max-Age: 86400
How to configure Cross-Origin Resource Sharing
Let’s see how to Cross-Origin Resource Sharing (CORS) in popular web servers like Apache and Nginx.
Enabling CORS in Apache
Setting up Cross-Origin Resource Sharing in Apache is pretty easy.
Start by opening your site’s config file under Apache, this may be an individual .conf file or the Apache main .conf file.
Look for the VirtualHost section and add CORS settings right there:
Header set Access-Control-Allow-Origin "*" Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT" Header always set Access-Control-Max-Age "1000" Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
The settings above are just an example, remember to tweak them according to your needs.
Restart Apache to apply the new settings:
systemctl restart apache2
If you’re using .htaccess you can set the rules the same way, and you won’t need to restart Apache to apply them.
Setting up CORS in Nginx
Setting up CORS in Nginx is very straightforward.
Start by opening your site’s config file under Nginx, it’s located usually in your Nginx’s sites-available directory or conf.d directory.
Look for the Server section and add CORS rules right there:
add_header 'Access-Control-Allow-Origin' '*'; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS'; add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range'; add_header 'Access-Control-Allow-Credentials' 'true';
Our settings above are just an example, remember to tweak them according to your needs.
Test your new Nginx config and restart it to apply the new settings:
nginx -t systemctl restart nginx
Configuring CORS on IIS
Setting up the CORS header on IIS can be done quickly and easily.
- Open the IIS Manager and select the site where you wish to configure the CORS header.
- Open HTTP Response Headers and click on Add.
- Here are the headers you may need to add, depending on your requirements. Remember that these are examples.
- Allow Origins:
- Name: Access-Control-Allow-Origin
- Value: add the allowed origin(s), for instance https://example.com or use * to allow all origins (not recommended for production).
- Allow Methods:
- Name: Access-Control-Allow-Methods
- Value: GET, POST, OPTIONS
- Allow Credentials:
- Name: Access-Control-Allow-Credentials
- Value: true
- Save the changes to apply the new header.
Testing Cross-Origin Resource Sharing
Testing your current Cross-Origin Resource Sharing settings is pretty easy, just follow our steps:
- Access our web security scanner.
- Input your domain in the scan box.
- Click the two boxes below, which are called ‘Clear cache’ and ‘Follow redirects’.
- Now hit the Scan button.
- Scroll down and look for the section named ‘HTTP Security Headers’, and check your ‘Cross-Origin Resource Sharing’ test results: if you get a ‘Passed’ in green then you’re good to go, but if you get a ‘Failed’ in red then you need to update your current settings.
Cross-Origin Resource Sharing (CORS) FAQ
Is it mandatory to enable CORS?
No, but you’ll need it if you want to allow web pages from one domain to access resources on another domain. If you want to know if your site has it enabled, you can find out using our security misconfiguration scanner, as explained above.
Is Cross-Origin Resource Sharing a vulnerability?
No, CORS is a security measure. It helps protect websites from malicious cross-origin requests by allowing or blocking access to resources based on the server’s configuration. Without CORS, browsers would restrict cross-origin requests by default.
Is Cross-Origin Resource Sharing still relevant?
Yes, CORS is still relevant and widely used. As websites continue to evolve and rely on various services, enabling secure cross-origin communication remains a key point for maintaining a seamless user experience, while also ensuring data security.
Does Cross-Origin Resource Sharing protect the server or the client?
CORS primarily protects the server. It ensures that only authorized domains can access resources on a server, preventing potential security threats. While CORS doesn’t directly protect the client, it contributes to a safer web environment by controlling cross-origin resource requests.
Can Cross-Origin Resource Sharing be configured selectively for specific resources?
Yes, CORS can be configured on a per-resource basis. Servers can specify which resources are accessible to requests from different origins by setting appropriate CORS headers. This allows for great control over cross-origin access, making sure that only necessary resources are exposed while others remain protected.
What are some challenges of implementing Cross-Origin Resource Sharing?
Implementing CORS can be complex and lead to potential security risks if not configured properly. Some challenges include misconfigurations leading to unintended access, the need for testing across different browsers and environments, and potential performance issues due to additional HTTP requests and header processing.
Summary
Cross-Origin Resource Sharing (CORS) is an important security feature, regulating resource requests between different domains and preventing unauthorized access. When a browser initiates a request to a domain other than the present page, CORS headers are sent, specifying if the request should be approved or rejected. Properly configuring CORS headers is very important to ensure secure and seamless interactions across different domains.
It operates by servers specifying, in advance, which websites are permitted to access their resources through special rules in HTTP headers, such as “Access-Control-Allow-Origin.” Enabling CORS can be safe if done correctly, but improper configuration may expose the server to risks by allowing unauthorized access.