Improve CORS config: block all if no origins specified

Refined CORS policy in Program.cs for better security. In development, all origins are allowed. In production, only configured origins are allowed; if none are specified, all cross-origin requests are blocked by default. Switched to Array.Empty<string>() for clarity.
This commit is contained in:
OlgunR
2026-01-19 17:08:55 +01:00
parent 7a78a48d03
commit 6b89f7bd72

View File

@@ -1,6 +1,7 @@
using DbFirst.API.Middleware;
using DbFirst.Application;
using DbFirst.Application.Repositories;
using DbFirst.Domain;
using DbFirst.Infrastructure;
using DbFirst.Infrastructure.Repositories;
@@ -15,10 +16,10 @@ builder.Services.AddSwaggerGen();
// In any case, dont let them to free to use without cors. if there is no origin specified, block all.
// In development you can keep it easy.
builder.Services.AddCors(options =>
{
{
options.AddDefaultPolicy(policy =>
{
if(builder.Environment.IsDevelopment())
if (builder.Environment.IsDevelopment())
{
policy.AllowAnyOrigin()
.AllowAnyHeader()
@@ -26,10 +27,14 @@ builder.Services.AddCors(options =>
}
else
{
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
policy.WithOrigins(origins)
.AllowAnyHeader()
.AllowAnyMethod();
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
if (origins.Length > 0)
{
policy.WithOrigins(origins)
.AllowAnyHeader()
.AllowAnyMethod();
}
// if no origins configured, deny all by leaving policy without allowances
}
});
});