How to Enable Cors in ASP.NET Core

How to enable CORS in ASP.NET Core

For ASP.NET Core 6:

var  MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://example.com",
"http://www.contoso.com");
});
});

// services.AddResponseCaching();

builder.Services.AddControllers();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();

app.UseCors(MyAllowSpecificOrigins);

app.UseAuthorization();

app.MapControllers();

app.Run();

See the official docs for more samples.


For ASP.NET Core 3.1 and 5.0:

You have to configure a CORS policy at application startup in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("http://example.com")
.AllowAnyMethod()
.AllowAnyHeader();
}));

// ...
}

The CorsPolicyBuilder in builder allows you to configure the policy to your needs. You can now use this name to apply the policy to controllers and actions:

[EnableCors("MyPolicy")]

Or apply it to every request:

public void Configure(IApplicationBuilder app)
{
app.UseCors("MyPolicy");

// ...

// This should always be called last to ensure that
// middleware is registered in the correct order.
app.UseMvc();
}

How to enable cors in ASP.NET Core 6.0 Web API project?

The code that you posted seems to work fine. I pasted the code into a new .NET 6 project and the CORS headers are added in the response when a request like below is send from the browser.

fetch('http://localhost:7107/Weatherforecast').then(res => res.json()).then(e => console.log(e))

Results in the following response:

Sample Image

How to enable CORS in ASP.net Core WebAPI

Because you have a very simple CORS policy (Allow all requests from XXX domain), you don't need to make it so complicated. Try doing the following first (A very basic implementation of CORS).

If you haven't already, install the CORS nuget package.

Install-Package Microsoft.AspNetCore.Cors

In the ConfigureServices method of your startup.cs, add the CORS services.

public void ConfigureServices(IServiceCollection services)
{
services.AddCors(); // Make sure you call this previous to AddMvc
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

Then in your Configure method of your startup.cs, add the following :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Make sure you call this before calling app.UseMvc()
app.UseCors(
options => options.WithOrigins("http://example.com").AllowAnyMethod()
);

app.UseMvc();
}

Now give it a go. Policies are for when you want different policies for different actions (e.g. different hosts or different headers). For your simple example you really don't need it. Start with this simple example and tweak as you need to from there.

Further reading : http://dotnetcoretutorials.com/2017/01/03/enabling-cors-asp-net-core/

How to enable Cors for every type of request in asp.net core 3.1

you need to allow any origin which you do with the following:

builder.AllowAnyOrigin()

Any Origin with AllowCredentials

not allowing credentials to be sent from any origin is by design.

You can get around this by using the following

builder.SetIsOriginAllowed(_ => true)

I dont think it is a great solution because it removes the benefit of useCredentials().

Note

useCredentials is not required for sending a JWT in the header. It is for if you need to send cookies in the request. Allowing any origin and enabling useCredentials can lead to security vunerabilities which is why it is not allowed by default.

For more information you should read

What exactly does the Access-Control-Allow-Credentials header do?

and

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

How to enable CORS in Asp.Net Core 3.0 WebAPI

The order of precedence for Cors should be before adding controllers. It should be added as define in the official documentation: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

Follow this code:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200", "http://localhost:44349")
.AllowAnyMethod()
.AllowAnyHeader();
//.AllowCredentials());
});

services.AddControllers();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

app.UseHttpsRedirection();
app.UseRouting();

app.UseCors("CorsPolicy");
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}

As per the official documentation, it must be noted that:

Specifying AllowAnyOrigin and AllowCredentials is an insecure
configuration and can result in cross-site request forgery. The CORS
service returns an invalid CORS response when an app is configured
with both methods.

ASP.NET Core Disable CORS for specific controllers

In your example, you've done two things of note in setting up the WebHost:

  1. Created a custom CORS policy named AllowCors.
  2. Added the CORS middleware to the pipeline, which uses AllowCors as its policyName.

Here's a snippet of the Invoke function that gets called for the CORS middleware:

public async Task Invoke(HttpContext context)
{
if (context.Request.Headers.ContainsKey(CorsConstants.Origin))
{
var corsPolicy = _policy ?? await _corsPolicyProvider?.GetPolicyAsync(context, _corsPolicyName);
if (corsPolicy != null)
{
var corsResult = _corsService.EvaluatePolicy(context, corsPolicy);
_corsService.ApplyResult(corsResult, context.Response);

...

In this snippet, _policy is null and _corsPolicyName is AllowCors. Because AllowCors is the name of a valid policy that was added using AddCors, this results in the CORS middleware applying the revelant CORS headers for all requests.

In your example, you've also used both [EnableCors(...)] and [DisableCors], which are MVC authorisation filters. By doing this, you're mostly just telling MVC to take care of CORS, which is independent of the CORS middleware you've added to the WebHost's pipeline.

This combination of MVC and CORS middleware is what is causing your unexpected results. The middleware is adding the CORS headers to your request regardless of whether or not you're asking it not to by using the [DisableCors] attribute - the CORS middleware has no idea that this MVC concept (a filter) even exists.

Based on this information, you can fix your issue in one of two ways:

  1. Remove the policyName parameter from your call to UseCors.
  2. Remove the UseCors call itself.

With option 1, the UseCors middleware will use the default policy, if it's been configured using AddDefaultPolicy on the CorsOptions passed into the AddCors delegate.

With option 2, the CORS middleware is simply excluded from the pipeline. This will also work in your example, because you've used [EnableCors(...)] where you need it. This also means that you don't need to use [DisableCors] at all - it'll default to not adding the CORS headers.

This raises the question: When would [DisableCors] be useful? As an example, consider the following basic controller:

[EnableCors("AllowCors")]
public class ExampleController : ControllerBase
{
public IActionResult Action1() =>
...

public IActionResult Action2() =>
...
}

It's clear that in this example, both Action1 and Action2 will set the CORS headers. If you didn't want Action2 to set the headers, you could annotate it with [DisableCors].



Related Topics



Leave a reply



Submit