Skip to content

CORS setting in asp.net core 6.0 is not restricting the origins #42463

@nallu026

Description

@nallu026

Is there an existing issue for this?

  • I have searched the existing issues

Describe the bug

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. You help is much appreciated.

Steps To Reproduce

No response

Exceptions (if any)

No response

.NET Version

No response

Anything else?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs: Author FeedbackThe author of this issue needs to respond in order for us to continue investigating this issue.area-middlewareIncludes: URL rewrite, redirect, response cache/compression, session, and other general middlewaresfeature-corsThis issue is related to CORS

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions