CORS in .Net Core: .Net Core Security Part VI

FotoJet

You can find all .Net core posts here.

In these series of posts, we will see how to secure your .Net Core applications.

In this post, we will see what is CORS and how to enable CORS in your .Net Core application.

What is CORS?

Before going for the basic question “What is CORS?”, Let us take a scenario related to that.

Let us start with a very basic example.

Suppose there are 2 URLs which are as below:

http://mysite.com/abc.html
http://mysite.com/xyz.html

Here above both URLs looks almost same so let us call it “same origin”.

Now, after making little twist we are having some more URLs as below:

http://mysite.in //// You are having different domain.
http://www.mysite.com/xyz.html //// You have different sub domain
http://mysite.com:7000/abc.html //// Oh man you are having different ports

So, as we have seen in above examples URLs does not look similar so let us call it “Different origin”.

For example, if the CORS is not enabled you might get below exception while trying to access another domain using an ajax call:

XMLHttpRequest cannot load http://www.mysite.com/. No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

Why?

Because Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy and prevents a malicious site from reading sensitive data from another site.

But what if we want to allow other domains to access your APIs?

We have a savior here, which is CORS!

Now the question which we left in starting arrives like, “What is CORS?”

CORS stands for Cross-Origin Resource Sharing.

CORS is a W3C standard that allows a server to relax the same-origin policy. Using CORS, a server can explicitly allow some cross-origin requests while rejecting others.

In simple words – CORS gives the power to allow cross-domain calls from the domains which are specified

Till now I hope you would have understood what CORS is all about.

How does CORS work?

  • Once we use CORS, new HTTP headers are introduced which enables cross-origin requests
  • If the browser supports CORS, the browser sets those headers automatically for cross-origin requests
  • These cross-origin requests are then sent to the server, it contains origin header which includes the domain information
  • If everything goes well with the server, the server adds Access-Control-Allow-Origin header in the response
  • Value of the header Access-Control-Allow-Origin could be * in case if any origin should be allowed or the name of the domain when we want to allow any specific domain. i.e. Access-Control-Allow-Origin: http://mysite.com
  • If the response does not include the header Access-Control-Allow-Origin, the request fails

cors2

Image source – https://medium.com/@buddhiv/what-is-cors-or-cross-origin-resource-sharing-eccbfacaaa30

Coming to .Net Core, Does .Net Core supports CORS?

Yes, It surely does.

It is straightforward and easy to use CORS with .Net Core.

You just need to follow below steps:

  • Install Microsoft.AspNetCore.Cors Nuget package
  • Configure CORS in the ConfigureService method
  • Enable CORS using middleware in Configure method
  • Enable CORS in .Net Core MVC like enabling on Controllers or actions or globally

Install CORS Nuget package

To install Microsoft ASP.NET Core Cross-Origin Support, run the following command in the Package Manager Console:

PM> Install-package Microsoft.AspNetCore.Cors

Or search this on Nuget:

cors1

Configure CORS

First of all, we will add CORS service in Startup.cs file as below:


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

We can even create the policy and later we can use these policies runtime:


public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowMyOrigin",
builder => builder.WithOrigins("http://mysite.com"));
});
}

As you can see above, I have added WithOrigins method which Allows only specific origins to make requests.

Apart from this, there are other policy options which are as below:

  • AllowAnyOrigin() – Allows any origin
  • AllowAnyHeader() – Allows all HTTP headers in the request
  • WithHeaders() – Allows only specific headers
  • AllowAnyMethod() Allows all HTTP methods
  • WithMethods() – Allows only specific HTTP methods
  • AllowCredentials() – Credentials are passed with the cross-origin request, mostly used for cookie and HTTP authentication

Enable CORS

We can enable CORS by adding the CORS middleware in the Configure method of Startup.cs class, by this we are enabling the CORS for the entire application.


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

Note: Apply UseCors before UseMvc call so that the CORS middleware fires before any other endpoints.

Apply CORS in .Net Core application

Next step would be to apply our settings to our controllers or actions or globally.

For that there are mainly 3 options:

Use this in your attribute on the Controller’s action

Add [EnableCors] attribute above specific action method:


[EnableCors("AllowMyOrigin")]
public IEnumerable<string> Get()
{
  return new string[] { "value1", "value2" };
}							 			

Use this in your attribute on the Controller

Add [EnableCors] attribute above specific Controller:


[EnableCors("AllowMyOrigin")]

public class ValuesController : Controller

Apply CORS globally

We can apply CORS globally by adding CorsAuthorizationFilterFactory filter as shown below:


public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.Configure<MvcOptions>(options =>
{
options.Filters.Add(new CorsAuthorizationFilterFactory("AllowMyOrigin"));
});
}

Hope it helps.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s