Enabling CORS in ASP.NET Core

By default, browsers abide by the Same-Origin policy, which is that documents (Or in most cases scripts) cannot interact with a resource from another domain. It isolates, for example, a malicious script being able to do “too much”. A script loaded from a third party should not be able to call your own API. However in some cases this actually may be warranted.

Enter CORS

CORS or Cross-Origin Resource Sharing is a way to by-pass this limitation/security measure for legitimate reasons. The most common in the context of ASP.NET core is that you are building a Single Page Application, and you wish to host your API on another domain. For example your website is www.mywebsite.com and your API is api.mywebsite.com. Any scripts be they from jQuery, Angular, React, Backbone, whatever cannot make HTTP calls from www.mywebsite.com to api.mywebsite.com.

Configuring CORS In ASP.NET Core

Let’s get going and see how this works in ASP.NET Core

First you need to add the Microsoft Cors package from Nuget.

Install-Package Microsoft.AspNetCore.Cors

You then need to add the CORS services. In your startup.cs in your ConfigureServices method you should have something similar to the following :

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

Next you need to add the CORS middleware to your app. In your startup.cs you should have a Configure method. You need to have it similar to this :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
	app.UseCors( options => options.WithOrigins("http://www.mydomain.com").AllowAnyMethod() );

	app.UseMvc();
}

The options lambda is a fluent API so you can add/remove any extras you need. You can actually use the option “AllowAnyOrigin” to accept any domain, but I highly recommend you do not do this as it opens up cross origin calls from anyone. You can also limit cross origin calls to their HTTP Method (GET/PUT/POST etc) so you can only expose GET calls cross domain etc.

Important!

Two very important points.

  • Incase it wasn’t obvious, the above is to be done on your API not your web project!
  • Your protocol is important. http://www.mydomain.com is not the same as https://www.mydomain.com

2 thoughts on “Enabling CORS in ASP.NET Core”

    • Hi there. It’s kinda weird but in my case Windows auth doesn’t work even in core 1.1…
      Seems like I tried almost million ways – no result. Can you please share to me your example?

      Reply

Leave a Comment