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:
@@ -1,6 +1,7 @@
|
|||||||
using DbFirst.API.Middleware;
|
using DbFirst.API.Middleware;
|
||||||
using DbFirst.Application;
|
using DbFirst.Application;
|
||||||
using DbFirst.Application.Repositories;
|
using DbFirst.Application.Repositories;
|
||||||
|
using DbFirst.Domain;
|
||||||
using DbFirst.Infrastructure;
|
using DbFirst.Infrastructure;
|
||||||
using DbFirst.Infrastructure.Repositories;
|
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 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.
|
// In development you can keep it easy.
|
||||||
builder.Services.AddCors(options =>
|
builder.Services.AddCors(options =>
|
||||||
{
|
{
|
||||||
options.AddDefaultPolicy(policy =>
|
options.AddDefaultPolicy(policy =>
|
||||||
{
|
{
|
||||||
if(builder.Environment.IsDevelopment())
|
if (builder.Environment.IsDevelopment())
|
||||||
{
|
{
|
||||||
policy.AllowAnyOrigin()
|
policy.AllowAnyOrigin()
|
||||||
.AllowAnyHeader()
|
.AllowAnyHeader()
|
||||||
@@ -26,10 +27,14 @@ builder.Services.AddCors(options =>
|
|||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? [];
|
var origins = builder.Configuration.GetSection("Cors:AllowedOrigins").Get<string[]>() ?? Array.Empty<string>();
|
||||||
policy.WithOrigins(origins)
|
if (origins.Length > 0)
|
||||||
.AllowAnyHeader()
|
{
|
||||||
.AllowAnyMethod();
|
policy.WithOrigins(origins)
|
||||||
|
.AllowAnyHeader()
|
||||||
|
.AllowAnyMethod();
|
||||||
|
}
|
||||||
|
// if no origins configured, deny all by leaving policy without allowances
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user