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.
- {
- "version": "1.0.0-*",
- "buildOptions": {
- "preserveCompilationContext": true,
- "debugType": "portable",
- "emitEntryPoint": true
- },
- "dependencies": {},
- "frameworks": {
- "netcoreapp1.0": {
- "dependencies": {
- "Microsoft.NETCore.App": {
- "type": "platform",
- "version": "1.0.1"
- },
- "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
- "Microsoft.AspNetCore.Mvc": "1.0.0",
- "Microsoft.AspNetCore.Cors": "1.0.0"
- },
- "imports": "dnxcore50"
- }
- }
- }
Add the CORS Service in ConfigureServices method of startup class
- public void ConfigureServices(IServiceCollection services) {
- services.AddMvc();
- services.AddCors();
- }
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
- [EnableCors("AllowSpecificOrigin")]
- public IActionResult Index() {
- return View();
- }
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
- [EnableCors("AllowSpecificOrigin")]
- 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
- public void ConfigureServices(IServiceCollection services) {
- services.AddMvc();
- services.Configure < MvcOptions > (options => {
- options.Filters.Add(new CorsAuthorizationFilterFactory("AllowSpecificOrigin"));
- });
- }
Disable CORS
Using DisableCors attribute, we can disable CORS for a controller or an action.
Example
- [DisableCors]
- public IActionResult Index() {
- return View();
- }
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
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
- app.UseCors("AllowSpecificOrigin");
- }
The second method accepts the task of CorsPolicyBuilder type. By using the lamba expression, we can pass CorsPolicyBuilder object.
Example
- app.UseCors(option => option.WithOrigins("http://xyz.com"));
CorsPolicyBuilder has a fluent API, so we can chain method calls.
Example
- 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.
- app.UseCors(option => option.WithOrigins("http://xyz.com", "http://abc.com"));
Using the code given below, we can allow all the origins.
- app.UseCors(option =>option.AllowAnyOrigin());
- Set the allowed HTTP methods
Using WithMethods method of CorsPolicyBuilder class, we can set one or more specific methods.
- app.UseCors(option => option.WithMethods("GET", ”POST”));
Using the code given below, we can allow all the methods.
- app.UseCors(option => option.AllowAnyMethod());
- Set the allowed request headers
Using WithHeaders method of CorsPolicyBuilder class, we can set one or more specific headers.
- app.UseCors(option => option.WithHeaders("accept", "content-type", "origin"));
Using the code given below, we can allow all the headers.
- 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.
- 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.
- 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.
- 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
- public void ConfigureServices(IServiceCollection services) {
- services.AddCors(option => {
- option.AddPolicy("AllowSpecificOrigin", policy => policy.WithOrigins("http://abc.com"));
- option.AddPolicy("AllowGetMethod", policy => policy.WithMethods("GET"));
- });
- }
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {
- app.UseCors("AllowSpecificOrigin");
- }
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.