Security

What is CORS? What is it Used for?

CORS (Cross-Origin Resource Sharing) is a security protocol that controls how web pages make requests to a different domain than the one they originated from. Modern browsers enforce CORS when using APIs like XMLHttpRequest or fetch() to prevent unauthorized access to resources across different origins.

By default, browsers block cross-origin requests to protect users from malicious websites that could try to access sensitive data from other domains. CORS provides a controlled way to allow legitimate cross-origin requests while maintaining security. In this article, we will learn everything about CORS

What is CORS?

CORS stands for Cross-Origin Resource Sharing. It is a browser mechanism that provides controlled access to resources located on a different domain. This allows you to host static content at www.example.com while serving backend API requests from api.example.com. In such cases, when a resource from one domain requests data from another, it is known as a CORS request.

However, if not properly configured, CORS can expose your site to potential cross-domain attacks. This can lead to various security threats, such as Cross-Site Request Forgery (CSRF). To prevent such risks, it’s crucial to carefully configure CORS settings and allow only trusted origins to access your resources.

What is CORS and How Does it Work?

In Cross-Origin Resource Sharing (CORS), a script loaded from one origin attempts to make a request to another origin. Since browsers enforce same-origin policies for security reasons, CORS provides a way to allow specific cross-origin requests while preventing unauthorized access.

When a script tries to fetch data from a different origin, the browser first sends a preflight request using the HTTP OPTIONS method. This preflight request includes specific headers that inform the external server about the intended request, such as the HTTP method and any custom headers being used.

The external web server then validates the request by checking these headers. If the origin and requested method are allowed, the server responds with a set of CORS-specific HTTP headers. These headers define:

  • Which origins are permitted to access the resource.

  • What HTTP methods (e.g., GET, POST, PUT) are allowed.

  • Whether credentials like cookies or authentication tokens can be included in the request.

  • How long the browser should cache the CORS response to reduce unnecessary preflight requests.

If the validation is successful, the browser allows the actual request to proceed. Otherwise, it blocks the request to maintain security.

 

Different Types of HTTP Headers Used in CORS?

  • Access-Control-Allow-Origin – Access-Control-Allow-Origin reflects the “Origin” request header’s content, provided that it matches your access list.
  • Access-Control-Allow-Credentials – Access-Control-Allow-Credentials is a Boolean header. When set to true, it tells browsers to expose the response to the frontend JavaScript code. The credentials consist of cookies, authorization headers, and TLS client certificates.
  • Access-Control-Expose-Headers – The Access-Control-Expose-Headers is an HTTP response header. It determines which headers are to be exposed to the client scripts on the web.
  • Access-Control-Max-Age – The Access-Control-Max-Age is a header request. It determines how long the browser should retain the response to the cross-origin request’s preflight check in its cache. It helps reduce the overhead of future cross-origin requests.
  • Access-Control-Allow-Methods – The Access-Control-Allow-Method is a response header. It specifies one or more methods allowed when accessing a resource in response to a preflight request.
  • Access-Control-Allow-Headers – The Access-Control-Allow-Headers is another response header. It is used in response to a preflight request that includes the Access-Control-Request-Headers. It helps you determine which HTTP headers can be used during the actual request.

Are There Any Caveats For Using The “access control allow” Headers?

The “access control allow” headers are more complicated than the request headers. Because they lack proper implementation of the standard in most browsers. But what are the reasons? Let’s find them out.

Access-Control-Allow-Origin

At first glance, you might feel that the Access-Control-Allow-Origin header will support a comma-separated list or a wildcard subdomain. You think that you can statically set them to match all of the domains and subdomains. You feel that it would drastically reduce the number of times the browser needs to do preflight requests in a session. But unfortunately, it’s not the case. It will result in undefined behavior. For example, it supports a generic wildcard, which can disable the check in the browser altogether. As a result, the user data will be exposed to security threats.

What’s The Issue With The Wildcard?

If you set “Access-Control-Allow-Origin” to “*”, it will disable the same-origin policy. As a result, the browser will allow almost any requests from any script to the cross-origin resource. It can result in various issues. For example, the browser will no longer filter the origins. Hence, phishing sites can make a request to the resource. You never want it to happen.

You might be thinking about copying and pasting wildcards from popular forums. You feel it will help you properly use credentials, like Authorization HTTP headers or cookies. But in reality, they will make your cross-origin request fail. Because browsers don’t allow you to set the “Access-Control-Allow-Credentials” header if the “Access-Control-Allow-Origins” is set to a wildcard.

How About Reflecting Just The Origin?

You might be thinking about reflecting just the origin. It seems to be a smart approach. However, it completely bypasses the browser’s ability to prevent setting both the “Access-Control-Allow-Credentials” header and “Access-Control-Allow-Origins” wildcard.

What Is CORS – Principals Of A CORS Attack

The risks of an attack depend on the nature of the misconfiguration. Also, it depends on how you’re authenticating requests.

Types Of CORS Misconfigurations

There are two main types of CORS misconfigurations. They are:

  • Access-Control-Allow-Origin (ACAO): ACAO facilitates two-way communication with third-party websites. Any misconfiguration in it can exploit sensitive data, like usernames and passwords.
  • Access-Control-Allow-Credentials (ACAC): ACAC allows third-party websites to execute privileged actions like the authenticated users. For example, it enables the sites to change the password and contact information.

Impact and Risk

A misconfigured CORS can exploit your application to high-risk security threats. It allows third-party sites to carry out privileged requests through your website’s authenticated users. Therefore, it will significantly impact the confidentiality and integrity of sensitive data. For example, third-party sites can retrieve the credit card information saved by the user.

However, the risk is low for applications that deal with public data and require resources to be sent to other origins. However, you need to perform penetration testing to identify the appropriate risk level.

What Is CORS – What Is The Best Practice To Enable CORS?

You need to make valid requests to the cross-origin resource. Also, you have to ensure that the browser doesn’t allow every script it loads. You should be validating all of the access control request headers against appropriate access lists. However, it can be a bit tricky to implement, especially with the origin header. Also, the web is full of minor misconfigurations in parsing methods and bad regex. It leaves numerous sites exposed to security threats. But you can do it safely by keeping it simple. For example, you can compare a secure string against an array of trusted values. If it doesn’t match, you will get a “403 Forbidden” response.

You might want to support more than one “Origin.” However, you don’t have a lot of choices until browsers support a list of origins in the “access-control-allow-origin” header. However, you can reflect the validated “Origin” request header into the “access-control-allow-origin” header.

Libraries, Frameworks, & Reverse-Proxies

Most languages and web frameworks come with a pre-built solution to securely handle these issues. Therefore, you don’t have to give extra effort. However, few languages and frameworks don’t implement proper validation. Hence, you need to validate the operation of the library. If everything is fine, you can start using it.

Also, you can consider using an established web server, like Nginx or Apache, as a reverse proxy. You can use its filter rules to reflect the headers, provided that they satisfy the validation. However, keep in mind that they use regex. Hence, you need to be very careful with creating the search string. It will help you safely perform the validation. Many people make mistakes with the search string. As a result, they don’t get the expected results.

What Is CORS – How Can You Enable CORS On The Origin Server?

To enable CORS for static resources, like CSS, fonts, JavaScript, and images, you have to add this code to your server:

Apache

<IfModule mod_headers.c>
    <FilesMatch "\.(ttf|ttc|otf|eot|woff|font.css|css|js|gif|png|jpe?g|svg|svgz|ico|webp)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

Nginx

location ~ \.(ttf|ttc|otf|eot|woff|font.css|css|js|gif|png|jpe?g|svg|svgz|ico|webp)$ {
    add_header Access-Control-Allow-Origin "*";
}

Make sure you test your website with Firefox and Internet Explorer. They are known to cause problems if CORS is not handled correctly.

Does Cross-Origin Access Control Allow More Freedom?

Yes, it allows more freedom and functionality than purely same-origin requests. Also, it is more secure than simply allowing all cross-origin requests.

Apilayer offers a suite of highly productive APIs. By utilizing them, you can boost your development workflow. Try them now for free.

Enhancing CORS with APILayer APIs

While CORS controls cross-origin browser access, APILayer provides APIs that often interact across domains, making careful CORS management essential when integrating third-party data. Two APIs that particularly benefit from thoughtful CORS handling are:

1. Fixer API (Foreign Exchange Rates & Currency Conversion)

APILayer’s Fixer API delivers real-time and historical forex rates, including endpoints for /latest, /convert, /timeseries, and /fluctuation, catering to wide-ranging currency needs.
Use case: Imagine a front-end app fetching real-time exchange rates. To safely integrate this, you’d configure your CORS policy to allow only your app’s domain to request the Fixer endpoints. This keeps your currency logic secure and seamless.

2. Number Verification API (Global Phone Number Validation & Lookup)

The Number Verification API offers comprehensive validation and carrier/location metadata across 232 countries.
Use case: Let’s say your web form validates phone numbers client-side. You might proxy requests server-side to avoid exposing CORS directly, keeping your validation process robust and secure, while still taking advantage of quick, accurate validation.

Why These Fit Seamlessly

  • Fixer API adds real-world interaction complexity, external data fetching that hinges on proper CORS setup.

Number Verification API often needs to be sensitive, client-proxied, and secure, offering a natural example in the workflow.

FAQ

What is CORS and how does it work?

Cross-Origin Resource Sharing (CORS) is an HTTP-header-based mechanism. It allows a server to indicate any origins, like domain, scheme, or port, other than its own. It enables the server to explicitly whitelist certain origins. Thus, they can bypass the same-origin policy.

What is an example of CORS?

Let’s consider a scenario where you can host static content at a domain, like www.example.com. If you have a backend API, you can host it at a subdomain, like api.example.com. Here, a resource from one subdomain is requesting a resource from another subdomain.

What is CORS in web API?

Cross-origin resource sharing (CORS) is a browser security feature. It prevents cross-origin HTTP requests that are initiated from scripts from running in the browser.

Is CORS really needed?

Yes, CORS is really needed. It’s an important protocol for making cross-domain requests possible. It allows you to whitelist requests to your web server from certain locations. You can specify response headers like ‘Access-Control-Allow-Origin’.

Stay Connected​

Related posts
Security

How To Hide IP Address On iPhone And Mac?

Leave a Reply

Your email address will not be published. Required fields are marked *