Web Security: Cross-Origin Resource Sharing (CORS)

• Yash Gupta • Feb 24, 2025 • 5 mins read

Introduction:

Web security is a critical aspect of modern web development. One of the most common security mechanisms developers encounter is Cross-Origin Resource Sharing (CORS). This mechanism ensures that web applications follow security best practices when making requests to different domains. In this blog, we will explore CORS, why it is needed, how it works, common issues, and how to configure it properly.

What is CORS?

CORS is a security feature implemented by web browsers to prevent unauthorized requests from one domain (origin) to another. By default, browsers enforce the same-origin policy, which restricts web pages from making requests to a domain different from their own. CORS provides a controlled way to allow cross-origin requests when needed.

Example of a Same-Origin Policy Restriction:

If a website hosted at https://example.com tries to fetch data from https://api.example2.com, the browser will block the request unless https://api.example2.com explicitly allows it using CORS headers.

What is CORS?

Web applications often need to request resources from external APIs, third-party services, or even different subdomains. Some common scenarios where CORS is required include:

  • Fetching data from an external API (e.g., Google Maps API, weather data, etc.)
  • Integrating with cloud storage services (e.g., fetching images from Amazon S3)
  • Running frontend and backend on different domains (e.g., React frontend on localhost:3000 calling an API on localhost:5000)
    Without CORS, these legitimate requests would be blocked by the browser’s security policies.

How CORS Works?

CORS operates through HTTP headers that dictate how cross-origin requests should be handled. These headers are set by the server receiving the request. Some key CORS headers include:

  • Access-Control-Allow-Origin:
This header defines which domains are allowed to access the resource. Example:

Access-Control-Allow-Origin: https://example.com

To allow all domains:

Access-Control-Allow-Origin 

  • Access-Control-Allow-Methods:

This specifies the HTTP methods that are allowed for cross-origin

requests.Access-Control-Allow-Methods: GET, POST, PUT, DELETE

  • Access-Control-Allow-Headers:

This header specifies which HTTP headers can be included in the request.

Access-Control-Allow-Headers: Content-Type, Authorization

Configuring CORS in Different Technologies

CORS in Node.js (Express)

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

app.use(cors({
origin: 'https://example.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
}));

app.listen(5000, () => console.log('Server running on port 5000'));

CORS in ASP.NET Core

services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", builder =>
{
builder.WithOrigins("https://example.com")
.AllowAnyMethod()
.AllowAnyHeader();
});
});

Common CORS Errors and Fixes

  • CORS Policy Blocked Error

Error message:

Access to fetch at 'https://api.example2.com' from origin 'https://example.com' has been blocked by CORS policy.

Solution: Ensure the API server includes the correct Access-Control-Allow-Origin header.

  • Preflight Request Fails

Error message:

OPTIONS https://api.example2.com/data 405 (Method Not Allowed)

Solution: Ensure the server allows the OPTIONS method and includes Access-Control-Allow-Methods.

  • Wildcard (*) and Credentials Issue

Error message:

Credential is not supported if Access-Control-Allow-Origin is '*'.

Solution: If using credentials (cookies, authentication tokens), specify an explicit origin instead of *.

Access-Control-Allow-Origin: https://example.com
Access-Control-Allow-Credentials: true

Conclusion

CORS is essential for web security. It ensures controlled access between different origins while preventing unauthorized cross-origin requests. Proper configuration is key to enabling secure and functional cross-origin communication. Whether you’re working with Node.js, ASP.NET Core, or Flask, understanding and correctly implementing CORS will help you avoid common pitfalls and security vulnerabilities.

By managing CORS policies effectively, developers can ensure seamless interaction between frontend and backend applications without compromising security. 🚀

Yash Gupta
I am passionate about tech and coding. I share expert insights on Test Automation (Selenium, Cypress, Playwright), API Automation, JavaScript, Python, Svelte, Vue.js, ReactJS, Angular, Flutter, and more. Stay updated with the latest trends! 🚀