CORS & Security Headers
Fix "CORS error" + stop hackers with 3 lines of code.
localhost:3000 calls API on localhost:5000. Browser blocks it: "CORS error". Your frontend team is stuck.1. CORS Explained in 20 Seconds - Zomato Example
Browser Rule: For security, JS can only call APIs from same "origin" = Protocol + Domain + Port.
Zomato App: https://zomato.com calls https://api.zomato.com. Different domains! Browser blocks by default.
Solution: API server must send header: Access-Control-Allow-Origin: https://zomato.com = "I trust this site".
๐ฏ CORS = Server Tells Browser Who to Trust
Browser asks API: "Can localhost:3000 call you?" API replies: "Yes" via headers. If API says nothing, browser says "No". CORS is enforced by browser, not server. Postman works because Postman isn't a browser.
2. Fix CORS in 3 Lines - Program.cs
var builder = WebApplication.CreateBuilder(args);
// 1. Define Policy
builder.Services.AddCors(options => {
options.AddPolicy("AllowReactApp", policy => {
policy.WithOrigins("http://localhost:3000", "https://myapp.com")
.AllowAnyHeader()
.AllowAnyMethod(); // GET, POST, PUT, DELETE
});
});
var app = builder.Build();
// 2. Use it - ORDER MATTERS: Before Auth, Before Controllers
app.UseCors("AllowReactApp");
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Done. React app can now call API. No more red errors.
3. Security Headers - Stop XSS + Clickjacking in 1 Middleware
Problem: Your API might return HTML. Hackers iframe it, steal clicks. Or inject scripts.
Fix: Add security headers to every response.
// Program.cs - Add after UseCors
app.Use(async (context, next) => {
context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
context.Response.Headers.Add("X-Frame-Options", "DENY");
context.Response.Headers.Add("X-XSS-Protection", "1; mode=block");
context.Response.Headers.Add("Referrer-Policy", "strict-origin-when-cross-origin");
context.Response.Headers.Add("Content-Security-Policy", "default-src 'self'");
await next();
});
Result: Scan your API on securityheaders.com = A+ rating. Takes 5 mins.
policy.AllowAnyOrigin() in production. Why you're fired: Any website can call your API, steal user data if user is logged in via cookies. CSRF attack.
Fix: NEVER use AllowAnyOrigin with credentials. Always specify:
WithOrigins("https://myapp.com"). For public APIs, it's OK, but not if using cookies/JWT from browser.
No comments yet. Be the first to share your thoughts!