Top 10 Best Practices for CORS – Cross-Origin Resource Sharing

Top 10 Best Practices for CORS Cross Origin Resource Sharing

Today, this article will help you to go over the Top 10 Best Practices for CORS -Cross-Origin Resource Sharing.

By design, Web applications execute a cross-origin HTTP request when it requests a resource that has a different origin or domain. This is due to security reasons and as per design specifications.

What is CORS

CORS (Cross-origin resource sharing) is a security feature that limits how web pages can communicate with resources from other domains.

Web browsers are required to use CORS by design. Implementing the same-origin policy, which prohibits web pages from making requests to domains other than their own, prevents unwanted access to resources.

Better Controlled cross-origin requests are made possible by CORS, which enables servers to specify which origins (domains) are permitted access to their resources. As a result, users are shielded from potential security threats like cross-site request forgery (CSRF) and cross-site scripting (XSS) attacks while enabling safe communication between various origins.

Today in this article, we will go over below aspects,

Enable CORS on the Server

Configure the server to include the necessary CORS headers in the HTTP response, allowing specific origins to access the resources.

Example – .NET C#

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...

....
    app.UseCors(builder =>
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader());
    
....
...
}

Example – Node.js

const express = require('express');
const app = express();
const cors = require('cors');
...
...

app.use(cors());

....
....

});

Example – Java

import org.springframework.web.bind.annotation.CrossOrigin;

// Enable CORS for a specific controller
@CrossOrigin("*")
@RestController
public class WeatherController {
 // ...
}

Above both examples we are allowing any origin, any HTTP method, and any header to access your resources.

For production use, consider Restrict Origins the origin to specific origins, methods, and headers to enhance security.

Restrict Origins in CORS

Only allow trusted origins to access your resources by specifying the allowed origins using the “Access-Control-Allow-Origin” header.

Please specify the origins that are allowed to access your server resources.

This will limit cross-origin requests to only those domains that you explicitly trust.

Depending on the server-side technology you are using, the implementation may vary, but the concept remains the same.

Example – .NET C#

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...

....
    app.UseCors(builder =>
        builder.WithOrigins("https://www.thecodebuzz.com",)
               .AllowAnyMethod()
               .AllowAnyHeader());
    
....
...
}

Example – Node.js

const express = require('express');
const app = express();
const cors = require('cors');
...
...

const allowedOrigins = ["http://TheCodebuzz.com", "http://TheCodebuzz.test.com"];

// Enable CORS for specific origins
app.use(cors({
    origin: function (origin, callback) {
        if (!origin || allowedOrigins.includes(origin)) {
            callback(null, true);
        } else {
            callback(new Error('Not allowed by CORS'));
        }
    }
}));

....
....

});

Example – Java

import org.springframework.web.bind.annotation.CrossOrigin;

// Enable CORS for a specific controller
@RestController
public class WeatherController {
// Restrict origins for this specific controller
@CrossOrigin(origins = {"http://TheCodebuzz.com", "http://Test.TheCodebuzz.com"})
 // ...
}

Validate User Input or Input request

Sanitizing input requests in an application is crucial to prevent security vulnerabilities such as SQL injection, cross-site scripting (XSS), and other malicious attacks.

Proper input validation and sanitization help ensure the integrity and security of your application. Here’s how you can sanitize input requests in your application.

Validate all incoming data against expected formats and constraints. Reject or sanitize any input that doesn’t conform to these requirements.

Handle CORS Errors

Cross-Origin Resource Sharing (CORS) errors occur when a web application makes a request to a different domain than the one from which the application was served.

Browsers enforce the same-origin policy to prevent unauthorized access, but CORS allows controlled access to resources from other origins.

CORS handling can vary based on the programming language, framework, and server you are using.

Always refer to the documentation of your specific technology stack for accurate and detailed instructions on handling CORS.

Handle CORS errors on the server side. If a request violates CORS policies, respond with an appropriate error status (e.g., 403 Forbidden) and an error message.

Optimize CORS by Caching Pre-flight Requests

Preflight requests in CORS (Cross-Origin Resource Sharing) are OPTIONS requests sent by browsers before certain cross-origin requests.

These checks determine if the actual request is safe to send. While preflight requests cannot be cached, their responses can be cached.

This can optimize subsequent CORS requests by allowing the browser to reuse the cached response without re-triggering preflight checks.

To cache preflight responses, ensure the appropriate caching headers (e.g., Cache-Control, Expires) are set in the server’s response to the OPTIONS request.

HTTP Safe Methods

Preferring safe HTTP methods for Cross-Origin Resource Sharing (CORS) is a best practice that enhances security and simplifies cross-origin communication between web applications and APIs.

Safe methods include,

  • GET
  • HEAD
  • OPTIONS

The above safe HTTP methods are considered read-only and do not modify the server state. These Safe methods are idempotent, meaning that making multiple identical requests will have the same effect as making a single.

Security Audits of CORS policy

Periodically review and update CORS settings based on evolving security requirements to maintain a secure web application.

By following these best practices, you can ensure secure and controlled communication between different origins in your web applications, preventing unauthorized access and potential security risks associated with Cross-Origin Resource Sharing.

Summary

CORS, or Cross-Origin Resource Sharing, is a security feature implemented in web browsers to control how web pages can interact with resources from different domains

By Adding CORS, you can ensure secure and steady communication between different origins in your web applications while preventing potential security risks associated with Cross-Origin Resource Sharing.

That’s all! Happy coding!

Does this help you fix your issue?

Do you have any better solutions or suggestions? Please sound off your comments below.



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

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