Skip to main content

CORS (Cross-Origin Resource Sharing)

Overview

CORS is a security feature that allows or restricts resources on a web server to be requested from another domain.

Same-Origin Policy

Browsers block requests from:

  • Different domain: api.example.comapp.example.com
  • Different protocol: https://http://
  • Different port: :5000:3000

CORS Configuration

1. Basic CORS Setup

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.WithOrigins("https://example.com")
.AllowAnyMethod()
.AllowAnyHeader();
});
});

var app = builder.Build();

app.UseCors(); // Must be before UseAuthorization
app.UseAuthentication();
app.UseAuthorization();

2. Named Policies

builder.Services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", policy =>
{
policy.WithOrigins("https://example.com", "https://app.example.com")
.WithMethods("GET", "POST")
.WithHeaders("Content-Type", "Authorization");
});

options.AddPolicy("DevelopmentPolicy", policy =>
{
policy.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});

// Apply globally
app.UseCors("AllowSpecificOrigin");

// Or per endpoint
app.MapGet("/api/data", () => "Data")
.RequireCors("AllowSpecificOrigin");

3. Allow Credentials

policy.WithOrigins("https://example.com")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials(); // Allows cookies, auth headers

⚠️ Cannot use AllowAnyOrigin() with AllowCredentials()

4. Expose Headers

policy.WithOrigins("https://example.com")
.WithExposedHeaders("X-Custom-Header", "X-Response-Time");

5. Preflight Cache

policy.WithOrigins("https://example.com")
.SetPreflightMaxAge(TimeSpan.FromMinutes(10));

Environment-specific CORS

if (app.Environment.IsDevelopment())
{
app.UseCors(policy => policy
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
}
else
{
app.UseCors("ProductionPolicy");
}

CORS Best Practices

  1. Be Specific: List allowed origins explicitly
  2. Avoid AllowAnyOrigin in production
  3. Use HTTPS: Always in production
  4. Credentials: Only when necessary
  5. Preflight Cache: Reduce OPTIONS requests

Common Issues

Issue: CORS still blocked

  • Check middleware order (UseCors before UseAuthorization)
  • Verify origin matches exactly (including protocol and port)
  • Check if credentials are required

Issue: Preflight failures

  • Ensure OPTIONS method is allowed
  • Check if custom headers are allowed

Interview Questions

Q: What is CORS and why is it needed? A: CORS is Cross-Origin Resource Sharing, a security mechanism that controls which origins can access resources. It prevents malicious sites from making unauthorized requests.

Q: What's a preflight request? A: An OPTIONS request sent by the browser before the actual request to check if the CORS policy allows it.

Resources