Enabling Cross-Origin Requests In ASP.NET Core

Introduction

Browser security does not allow web pages to make AJAX requests to another domain. This prevention is called "same-origin policy". This prevents another site from reading sensitive data from another site.

Cross-Origin Resource Sharing (CORS) is a W3C standard. Using CORS, a Server can allow some cross-origin (domain) requests and reject others. CORS is more flexible and safer than the earlier techniques such as JSONP. In this article, we learn how to enable CORS in our ASP.NET Core Application.


Set up CORS in ASP.NET Core Application

To set up CORS in our Application, first we need to add "Microsoft.AspNetCore.Cors" dependency in our project.json file and using "dotnet restore", we can download the dependency.

  1. {  
  2.     "version""1.0.0-*",  
  3.     "buildOptions": {  
  4.         "preserveCompilationContext"true,  
  5.         "debugType""portable",  
  6.         "emitEntryPoint"true  
  7.     },  
  8.     "dependencies": {},  
  9.     "frameworks": {  
  10.         "netcoreapp1.0": {  
  11.             "dependencies": {  
  12.                 "Microsoft.NETCore.App": {  
  13.                     "type""platform",  
  14.                     "version""1.0.1"  
  15.                 },  
  16.                 "Microsoft.AspNetCore.Server.Kestrel""1.0.0",  
  17.                 "Microsoft.AspNetCore.Mvc""1.0.0",  
  18.                 "Microsoft.AspNetCore.Cors""1.0.0"  
  19.             },  
  20.             "imports""dnxcore50"  
  21.         }  
  22.     }  
  23. }  

Add the CORS Service in ConfigureServices method of startup class

  1. public void ConfigureServices(IServiceCollection services) {  
  2.     services.AddMvc();  
  3.     services.AddCors();  
  4. }  

Enable CROS in MVC

We can apply CORS in MVC per action, per controller or globally. MVC CORS Services are different from the Middleware CORS Service.

Apply CORS per Action

To specify CORS per action, add EnableCors attribute on top of the action. The EnableCors attribute accepts the policy name as an argument. We will learn CORS policy later on in this article.

Example

  1. [EnableCors("AllowSpecificOrigin")]  
  2. public IActionResult Index() {  
  3.     return View();  
  4. }  

Apply CORS per Controller

To specify CORS to the specific controller, add EnableCors attribute to the controller class. This applies the CORS to every action method of the controller.

Example

  1. [EnableCors("AllowSpecificOrigin")]  
  2. public class HomeController: Controller {}  

Apply CORS to entire Application

We can also enable CORS Application wide (globally). It applies CORS to all the controllers by adding CorsAuthorizationFilterFactory filter to the global filter collection in ConfigureService method of Starpup class.

Example

  1. public void ConfigureServices(IServiceCollection services) {  
  2.     services.AddMvc();  
  3.     services.Configure < MvcOptions > (options => {  
  4.         options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));  
  5.     });  
  6. }  

Disable CORS

Using DisableCors attribute, we can disable CORS for a controller or an action.

Example

  1. [DisableCors]  
  2. public IActionResult Index() {  
  3.     return View();  
  4. }  

Enable CORS in middleware

To enable CORS in middleware, we need to add the request pipeline, using UseCors extension method. It is similar to MVC and we can specify a cross origin policy when adding the CORS middleware, using the CorsPolicyBuilder class.

UseCors method has two overload versions, where the first one only accepts the poly name as an argument. Hence with this method, we need to pass the CORS policy name as a string.

Example

  1. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {  
  2.     app.UseCors("AllowSpecificOrigin");  
  3. }  

The second method accepts the task of CorsPolicyBuilder type. By using the lamba expression, we can pass CorsPolicyBuilder object.

Example

  1. app.UseCors(option => option.WithOrigins("http://xyz.com"));  

CorsPolicyBuilder has a fluent API, so we can chain method calls.

Example

  1. app.UseCors(option => option.WithOrigins("http://xyz.com").AllowAnyMethod());  

CORS policy options

Following are the options, which we can set in CORS policy

  • Set the allowed origins

    Using WithOrigins method of CorsPolicyBuilder class and we can set one or more specific origins.
    1. app.UseCors(option => option.WithOrigins("http://xyz.com""http://abc.com"));  
    Using the code given below, we can allow all the origins.
    1. app.UseCors(option =>option.AllowAnyOrigin());  
  • Set the allowed HTTP methods

    Using WithMethods method of CorsPolicyBuilder class, we can set one or more specific methods.
    1. app.UseCors(option => option.WithMethods("GET", ”POST”));  
    Using the code given below, we can allow all the methods.
    1. app.UseCors(option => option.AllowAnyMethod());  
  • Set the allowed request headers

    Using WithHeaders method of CorsPolicyBuilder class, we can set one or more specific headers.
    1. app.UseCors(option => option.WithHeaders("accept""content-type""origin"));    
    Using the code given below, we can allow all the headers.
    1. app.UseCors(option => option.AllowAnyHeader());  
  • Set the exposed response headers

    The Browser does not expose the all the response headers to the Application.Using WithExposedHeaders method of CorsPolicyBuilder class, we can expose the additional headers.
    1. app.UseCors(option => option.WithExposedHeaders("x-custom-header"));  
  • Credentials in cross-origin requests

    The Browser does not send the credentials with a cross-origin request. In some case, we need to pass the credentials in a CORS request. The client must set XMLHttpRequest.withCredentials to true to send the credentials with a cross-origin request.

    The code given below is used to set the credentials in cross-origin requests.
    1. app.UseCors(option => option.AllowCredentials());  
  • Set the preflight expiration time

    The "Access-Control-Max-Age" header specifies how long the response to the preflight request can be cached. The code given below is used to set the preflight expiration time.
    1. app.UseCors(option => option.SetPreflightMaxAge(TimeSpan.FromSeconds(5000)));  

Define one or more named CORS policies and use the policy by name at run time

We can define set of CORS policies into the group and it is possible to select the policy run time. To achieve this, we need to add the group of the policy in ConfigureService method and select it at Configure method of Startup class.

Example

  1. public void ConfigureServices(IServiceCollection services) {  
  2.     services.AddCors(option => {  
  3.         option.AddPolicy("AllowSpecificOrigin", policy => policy.WithOrigins("http://abc.com"));  
  4.         option.AddPolicy("AllowGetMethod", policy => policy.WithMethods("GET"));  
  5.     });  
  6. }  
  7. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {  
  8.     app.UseCors("AllowSpecificOrigin");  
  9. }  

Summary

This article tried to explain how to enable CORS with ASP.NET Core Application for both MVC and middleware and different kind of CORS policies.