🔐 How to Secure Your API with CORS in .NET

Apurv upadhyay
2 min readNov 5, 2024

--

CORS

𝗪𝗵𝗮𝘁 𝗶𝘀 𝗖𝗢𝗥𝗦?

Imagine having a private club — you only allow selected people in to maintain security. Cross-Origin Resource Sharing (CORS) works similarly by controlling who can access your API from a different domain. This is especially important as it shields your web app from cross-site security attacks like CSRF while allowing safe connections from trusted sources.

Here’s how to master CORS in .NET Core and create a secure, flexible API experience.

🌐 Why Do We Need CORS?

In today’s web, applications interact across domains all the time, yet security is paramount. With CORS, we can:

Prevent Unwanted Access: Only specific domains can communicate with your app.

Control Exposure: Limit what parts of your application external domains can access.

Safeguard Users: Reduce exposure to attacks by controlling access with custom rules.

🔧 Setting Up CORS in .NET Core

1️⃣ Install the CORS Package

First, ensure you have the Microsoft.AspNetCore.Cors NuGet package in your project. It’s the gatekeeper.

2️⃣ Register and Configure CORS in Startup.cs

In the ConfigureServices method, add a CORS policy that defines who gets in:

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("OpenToEveryone", builder =>
builder.AllowAnyOrigin() // Open the doors to all origins
.AllowAnyMethod() // Allow all HTTP methods
.AllowAnyHeader()); // Permit any headers
});

services.AddControllers();
}

3️⃣ Apply the CORS Policy in Middleware

Implement the policy in Configure:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseCors("OpenToEveryone");
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => endpoints.MapControllers());
}

🎯 Making It More Exclusive: Custom CORS Policies

Let’s say we want to be a bit more selective and only allow access from specific sources. Here’s how to add custom rules:

Allow Specific Origins

Use .WithOrigins(“https://mydomain.com") to restrict access to selected domains.

Allow Specific Methods

Use .WithMethods(“GET”, “POST”) to allow only certain HTTP methods.

Allow Specific Headers

Use .WithHeaders(“Content-Type”) to limit which headers are allowed.

Here’s an example policy with restrictions:

options.AddPolicy("StrictPolicy", builder =>
builder.WithOrigins("https://mydomain.com")
.WithMethods("GET", "POST")
.WithHeaders("Content-Type"));

💥 Pro Tip: Avoid Over-Permissive Policies

While it’s tempting to use .AllowAnyOrigin() everywhere, opening too many doors compromises security. Opt for specific rules where possible to maintain robust protection.

🔐 The Takeaway

𝗖𝗢𝗥𝗦 𝗶𝗻 .𝗡𝗘𝗧 empowers you to secure your application while allowing controlled access. It’s about choosing the right balance — flexibility for authorized domains and protection from unwanted access. In a world where cross-origin threats are real, mastering CORS isn’t just an option; it’s a necessity.

Curious to see how CORS fits into your API security strategy? Give it a try and unlock safer, smarter web interactions!

❤️ Share Your Thoughts!

Feel free to repost ♻️ if you found this helpful. For more great content like this follow 🛠 Apurv Upadhyay. Until next time, happy coding! 🚀

#dotnet #cors #api #security #webdevelopment #backend

--

--

Apurv upadhyay
Apurv upadhyay

Written by Apurv upadhyay

Principal Software Engineer at PeerIslands • Microsoft Azure Certified Architect Expert & DevOps Specialist • 7x Azure Certified • ex-Microsoft, Bosch