What is CORS (Cross Origin Resource Sharing) and How to Configure?

Learn the benefits of Cross-Origin Resource Sharing, how to use it in your web development and the dangers of CORS misconfiguration.

By Tim Trott | Privacy & Security | February 17, 2023
1,316 words, estimated reading time 5 minutes.

In this article, we'll introduce you to cross-origin resource sharing (CORS) and show you how it can be used to improve the performance of your web applications.

Cross-Origin Resource Sharing (CORS) is an essential part of the web development process. It helps to ensure that resources can be shared freely across domains, allowing users access to the content they need, while also protecting the privacy of their data. This guide will provide a comprehensive overview of CORS and detailed instructions for implementation.

What is Cross-Origin Resource Sharing (CORS)

Cross-Origin Resource Sharing (CORS) is a technique used by web browsers to allow elements from one website to be loaded into another without intruding on the privacy of the second. This behaviour can be useful for two main reasons - loading scripts from other websites into your own and integrating third-party features into your site without exposing your user's personal data. However, if a website's CORS policy is improperly implemented, it also raises the possibility of cross-domain attacks.

CORS achieves this by establishing a set of rules that govern how cross-domain requests should be handled. It's important to understand these rules before implementing CORS on your website.

How to Implement Cross-Origin Resource Sharing (CORS) in Your Website

When enabling CORS on your web server, it's important to create a custom headers file that contains information regarding the resource requests and responses you want to handle as cross-origin requests. This includes the Access-Control-Allow-Origin header which should contain the list of domains or ports from which cross-domain requests should be allowed. It is important to note that any wildcard (*) entries here will allow access from any domain, so make sure to use either specific domains or narrow wildcards with caution. Additionally, the Access-Control-Allow-Methods header should be set to specify what types of media can be requested (i.e., GETs and POSTs).

For a successful cross-origin request between two domains, the browser must specify which headers are allowed in the preflight request. This is done by setting the Access-Control-Request-Headers header to a comma-separated list of header names which will be acceptable in the planned request. If you need certain behaviour from specific domains or URLs, it is important to allow them explicitly using this header instead of using general wildcards in Access-Control-Allow-Origin or Access-Control-Allow Methods. Doing so allows you to have more control over what resources can be accessed from which sources.

Configure your Web Server (Apache/IIS) Correctly

When setting up CORS on a web server, it's important to configure the server correctly. Depending on the type of web server you are using, there may be specific steps that need to be taken to ensure that requests from different domains are allowed access. You will also need to set specific headers to allow/restrict access to certain resources. Once you have configured your web server according to CORS rules, all requests should then be properly respected and cross-domain requests should return the expected results.

CORS on Apache

Simply add the following line to the Directory, Location, Files, or VirtualHost sections of your server configuration (often found in a *.conf file, such as httpd.conf or apache.conf), or inside a.htaccess file, to add the CORS authorisation to the header using Apache:

<IfModule mod_headers.c>
  Header set Access-Control-Allow-Origin "*"
</IfModule>

This will allow any origin site access to the resource. To only allow specific sites to access the resource, the origin domains can be specified in the header using a pipe delimiter.

<IfModule mod_headers.c>
  SetEnvIf Origin "http(s)?:/(www\.)?(google.com|staging.google.com|development.google.com)$" AccessControlAllowOrigin=$0
  Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
</IfModule>

Restarting Apache is required after making changes to configuration files. However, if the.htaccess file is added, there is no need to restart.

CORS on IIS

CORS is configured in ISS via a site or application web.config and has its own CORS configuration section within system.webServer.

Examples of settings are provided below to enable CORS for a website. All host origins are permitted by the * origin, however, later-included origins that begin with http://* are not. The CORS response is personalised with different CORS configurations as an example for the https://*.example.com host origin.

xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <cors enabled="true" failUnlistedOrigins="true">
            <add origin="*" />
            <add origin="https://*.example.com"
                 allowCredentials="true"
                 maxAge="120"> 
                <allowHeaders allowAllRequestedHeaders="true">
                    <add header="header1" />
                    <add header="header2" />
                </allowHeaders>
                <allowMethods>
                     <add method="DELETE" />
                </allowMethods>
                <exposeHeaders>
                    <add header="header1" />
                    <add header="header2" />
                </exposeHeaders>
            </add>
            <add origin="http://*" allowed="false" />
        </cors>
    </system.webServer>
</configuration>

CORS in PHP

You can still send the header from a PHP script even if you don't have access to Apache's configuration options. You must include the following in your PHP scripts.

The sample below should provide you with a brief summary of the HTTP headers that must be specified for CORS to function.

Initially, based on regular expressions, it establishes a list of permitted origin domains. The Origin header given in the client request, which can be found in $_SERVER['HTTP ORIGIN'], will be compared to this list. The necessary CORS headers will be set if one origin element from the list matches. The CORS pre-flight request is likewise taken care of by this configuration.

php
$allowedOrigins = array(
  '(http(s):/)?(www\.)?example\.com',
  '(http(s):/)?(www\.)?demo\.com'
);

if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN'] != '') {
  foreach ($allowedOrigins as $allowedOrigin) {
    if (preg_match('#' . $allowedOrigin . '#', $_SERVER['HTTP_ORIGIN'])) {
      header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
      header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
      header('Access-Control-Max-Age: 1000');
      header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
      break;
    }
  }
}

Build an authentication system so secured requests are handled properly

Implementing a secure authentication system is essential for proper cross-origin resource sharing. This ensures that the requests between two domains are properly authenticated and authorized, preventing malicious actors from accessing sensitive data through CORS exploits. When setting up your authentication system, it is important to ensure that the requests are carried out over HTTPS or other authenticated protocols. Additionally, you should also use trusted third-party services like OAuth2 and OpenID Connect to authenticate users securely.

What Is A CORS Error and How to Fix It

If you've ever tried to make a cross-origin request from your browser, you've probably run into a CORS error. CORS errors occur when your browser is unable to request another domain due to the same-origin policy. The same-origin policy is a security measure that prevents Javascript from making requests to domains other than the one it's currently on.

CORS Error - No 'Access-Control-Allow-Origin' header is present on the requested resource.
CORS Error - No 'Access-Control-Allow-Origin' header is present on the requested resource.

Fortunately, there are a few ways to work around CORS errors.

Typically, an error notice will appear. CORS policy on the browser console, followed by a reason like one of the following, has prohibited access to XMLHttpRequest.

  • No 'Access-Control-Allow-Origin' header present.
  • No 'Access-Control-Allow-Headers' headers present.
  • Method not supported under 'Access-Control-Allow-Methods' header.
  • Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

When the server fails to return the necessary CORS headers, a CORS error happens.

Errors are usually due to either the browser not sending the HTTP_ORIGIN header, or the HTTP_ORIGIN header does not specify the hostname correctly. The error is also seen when the server does not specify the correct header in the allow origin.

For instance, https://example.com tries to access resources on https://demo.com using an API request that is denied. The browser will show a CORS error since the response's Access-Control-Allow-Origin header does not include https://example.com.

Was this article helpful to you?
 

Related ArticlesThese articles may also be of interest to you

CommentsShare your thoughts in the comments below

If you enjoyed reading this article, or it helped you in some way, all I ask in return is you leave a comment below or share this page with your friends. Thank you.

There are no comments yet. Why not get the discussion started?

We respect your privacy, and will not make your email public. Learn how your comment data is processed.