CORS is advised to protect a website and its users from the security concerns associated with sharing resources across several domains, but what exactly is Cross-Origin Resources Sharing (CORS)?
We'll look at CORS in this post and why its proper implementation is crucial for creating safe websites and applications. Additionally, we'll explore preflight requests and typical use cases of CORS and discuss how to prevent your website against attacks.
What is Cross-Origin Resources Sharing (CORS)?
A cross-origin request is when a request is made to a server that is not the same origin as the website that is making the request. This can be a security issue because it can allow attackers to access data they should not have access to.
Cross-Origin Resource Sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which serviced the first resource. CORS is a mechanism that enables cross-origin requests.
Web browsers implement CORS using a standard called the Cross-Origin Resource Sharing Standard. Web browsers use the standard to determine whether or not to allow a cross-origin request. When a web browser sees a request for a resource with a different origin than the current page, it checks to see if the request is allowed by the CORS standard.
If the request is allowed, the browser sends the request to the server. The server then checks to see if the origin is allowed to access the resource. The server sends the resource back to the browser if the origin is allowed.
If the request is not allowed by the CORS standard, the browser will not send the request to the server.
In simple terms, It permits requests to be sent from one website to another in the browser, typically not allowed by a different browser policy known as the Same-Origin Policy (SOP).
What is the CORS Same-Origin Policy (SOP)?
The CORS same-origin policy is a significant security parameter of any modern browser. Its objective is to confine cross-origin interactions between scripts, documents, or media files from one origin to a web page with a distinct origin.
What is Meant by Origin?
Origin is defined by the scheme (protocol), hostname (domain), and URL port used to access it.
Let's suppose- http:anupamsingh.com:443 (Here in this URL- http is scheme), (anupamsingh is the domain name), and 443 is port. And when coming to the origin, the whole (http:anupamsingh.com:443) is denoted as the origin.
Also Read:-
Why Is It Needed to Use (CORS) Cross-Origin Resource Sharing?
A script that runs in a user's browser would typically only ever need to access resources from the exact origin (think about API calls to the same backend that served the JavaScript code in the first place). Therefore, it is suitable for security that JavaScript typically cannot access resources of other origins.
"Other origins" here refers to the fact that the URL being viewed is different from the location where the JavaScript is being executed by having:
- a different scheme, either http or HTTPS
- a different domain
- a different port
Cross-origin access, however, may be required or even desired in certain situations. React SPA calls with an API backend hosted on a different domain. CORS is necessary for web fonts to work.
CORS Request Types
CORS requests come in two types: "simple" and "preflight" requests and the browser chooses which to utilize. Usually, when creating requests to be sent to a server, you, as the developer, don't need to be concerned about this. However, you might notice the various requests in your network log, and since this could affect the performance of your application, it might be helpful for you to understand why and when these requests are sent.
In the following section, we'll examine what that means specifically. Let's Explore!!
Simple requests (GET, POST, and HEAD)
When a request satisfies a specific set of criteria, the browser classifies it as a simple request:
- It uses one of the following: GET, POST, or HEAD.
- A CORS safe-listed header is used.
- Only the following values are permitted for the Content-Type header:
application/x-www-form-urlencoded
,multipart/form-data
, ortext/plan
. - On any XMLHttpRequestUpload object, there aren't registered, event listeners.
- The request makes no use of any ReadableStream objects.
If the request meets these requirements, it is permitted to proceed normally, and the response is verified for the Access-Control-Allow-Origin header.
Preflight requests (OPTIONS)
A preflight request using the OPTIONS method will be made automatically by the browser if a request does not match the requirements for a simple request. The precise CORS capabilities of the server are ascertained by this call, which is then utilized to determine whether or not the planned CORS protocol is understood. Only send the request to the server if the OPTIONS call's outcome indicates that we cannot make it.
In the preflight request, the mode is set to OPTIONS, and a few headers are set to describe the actual request that will come next:
- Access-Control-Request-Method: The requested access control technique is specified by the access-control method (e.g., GET or POST)
- Access-Control-Request-Headers: A representation of the custom headers sent with the request.
- Origin: The typical origin header includes the script's current origin.
An illustration of such a request might be as follows:
# Request
curl -i -X OPTIONS localhost:3001/api/ping \
-H 'Access-Control-Request-Method: GET' \
-H 'Access-Control-Request-Headers: Content-Type, Accept' \
-H 'Origin: http://localhost:3000'
The above request demonstrates that "I would like to make a GET request with the Content-Type & Accept headers from http://localhost:3000 - is that possible"
In the response, the server will provide a few Access-Control-* headers that will state whether or not the subsequent request will be accepted. These consist of the following:
- Access-Control-Allow-Origin: The origin permitted to submit the request, or *if any origin may submit a request.
- Access-Control-Allow-Methods: a list of permitted HTTP methods, separated by commas.
- Access-Control-Allow-Headers: A list of custom headers permitted to be delivered, separated by commas.
- Access-Control-Max-Age: The access-control-max-age header indicates the maximum amount of time that the preflight answer can be cached before another call is placed.
The browser would review the response to determine whether to keep processing or cancel the request.
As a result, the following could be a response to the above example:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Vary: Access-Control-Request-Headers
Access-Control-Allow-Headers: Content-Type, Accept
Content-Length: 0
Date: Fri, 16 Nov 2022 11:41:08 GMT
Connection: keep-alive
The access-Control-Allow-Origin header permits the request to originate from any origin, whereas the Access-Control-Allow-Methods header specifies the accepted HTTP methods. It will only be listed if a specific HTTP method is accepted.
In this case, Access-Control-Allow-Headers returns the headers that the OPTIONS request requested. This shows that all of the requested titles are valid for transmission. For instance, if the server forbids the Accept header, the response wouldn't include it, and the browser would refuse the request.
Knowledge Base- Steps to Enable CORS on WordPress
Are you a WordPress user and want to enable CORS on your WordPress? We have the solution!! Look at the below-listed step to enable CORS for your WordPress REST API.
Follow the below steps to do so-
1. First, you have to open your functions.php file and add the codes below
<?php
function initCors( $value ) {
$origin_url = '*';
// Check if it's production environment
if (ENVIRONMENT === 'production') {
$origin_url = 'hxxps://anupamwordpresssite[.]com';
}
header( 'Access-Control-Allow-Origin: ' . $origin_url );
header( 'Access-Control-Allow-Methods: GET' );
header( 'Access-Control-Allow-Credentials: true' );
return $value;
}
In the above code, you must replace hxxps://anupamwordpresssite[.]com
with your live domain name. The above example will help check whether your environment is in production mode. It will automatically change the $origin_url value to your live domain if yes.
2. Now, Enable your CORS function
Add the next action, rest API init. This is added immediately after the newly built initCors function.
<?php
// ... initCors function
add_action( 'rest_api_init', function() {
remove_filter( 'rest_pre_serve_request', 'rest_send_cors_headers' );
add_filter( 'rest_pre_serve_request', initCors);
}, 15 );
3. Allow multiple origin support.
If you want to allow multiple origin support, create an array of allowed origins like the ones below.
// ... initCors function
function initCors( $value ) {
$origin = get_http_origin();
$allowed_origins = [ 'site1.exampledomain.com', 'site2.exampledomain.com', 'localhost:3000' ];
if ( $origin && in_array( $origin, $allowed_origins ) ) {
header( 'Access-Control-Allow-Origin: ' . esc_url_raw( $origin ) );
header( 'Access-Control-Allow-Methods: GET' );
header( 'Access-Control-Allow-Credentials: true' );
}
return $value;
}
Final Takeaway
This blog is all about Cross-Origin Resource Sharing ( CORS). CORS is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the resource originated. This mechanism is required to enable AJAX requests to be sent to a server other than the server that hosts the main page. Additionally, within this blog, we will find the steps to enable CORS on your WordPress.
Top comments (0)