1

I am trying to implement a CORS Policy in my ASP.NET Core Web API.

My Startup.cs file is as follows:

public void ConfigureServices(IServiceCollection services)
{
    options.AddPolicy("AllowSpecificOrigin", builder => builder.WithOrigins("https://google.com")
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowAnyOrigin());
    services.AddMvc()
        .AddApplicationPart(Assembly.Load(new AssemblyName("Proxy.Api.Application")))
        .AddJsonOptions(options =>
        {
            options.JsonSerializerOptions.WriteIndented = true;
        });
    services.AddControllers();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseRouting();
    app.UseCors("AllowSpecificOrigin");
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

I also added the controller method decorator attribute below:

[EnableCors("AllowSpecificOrigin")]
public Task<IActionResult> GetProxy([FromQuery] ProxyParams inputRequest)
{
   ....
}

Now to my understanding, this line:

options.AddPolicy("AllowSpecificOrigin", builder => builder.WithOrigins("https://google.com")

will only allow https://google.com domain to access my controller method with the EnableCors attribute decorator.

However, when I call the API endpoint locally through curl or fiddler, the method is still being hit and is returning 200. What am I missing? I've checked several posts but I'm kind of stuck.

Danny
  • 425
  • 7
  • 19

1 Answers1

0

You only care about CORS when you are dealing with browser.

It means you can make any request you want from a console app, web service, CURL, desktop app without any issue even if the CORS is not configured.

But if you try to open a Chrome console on a tab that is not Google and try to use the fetch API to contact your endpoint: it will fail.

I don't know what was your goal but it's really not a way to secure your API.

Edit By the way, if it's a "simple" request (without preflight request) like a simple GET, your endpoint will be hit and will return 200 anyway. It's only the browser that will deny it (you can check it through Fiddler).

More about CORS, Simple requests and preflight request there : HTTP request from Angular sent as OPTIONS instead of POST

Arcord
  • 1,724
  • 1
  • 11
  • 16