CORS setting in asp.net core 6.0 is not restricting the Origins

Nalswamy Kandaswamy 1 Reputation point
2022-06-28T07:56:07.863+00:00

Hi There,
I have created an ASP.NET Core 6.0 Web API and trying to set cors policy. I have applied policy only to allow few origins, but it is not working as expected instead it allows for all the sites which consumes this API. Can you please help me what I am missing?
Here is my program.cs file.

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddCors(options =>
{
options.AddPolicy("myPolicy",
policy =>
{
policy.WithOrigins("http://example.com").AllowAnyHeader().AllowAnyMethod();
});
});

builder.Services.AddControllers();

// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("defaultConnection")));

//builder.Services.AddCors();
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("myPolicy");
app.UseAuthorization();

app.MapControllers();

app.Run();

Expected Behavior

I was expected to allow access to the endpoints only for the requests from example.com, but it allows for all other sites too

Developer technologies ASP.NET ASP.NET Core
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.