What is CORS
In this article we will see in detail how to setup and implement CORS in a dotnet core application.
The full name of CORS is Cross Origin Resource Sharing. It is a W3C standard that allows a server to make cross-domain calls from the specified domains, while rejecting others By default due to browser security it prevents a web page from making one domain Ajax request to another domain.
This security in the software term is called the same-origin policy and does not allow a suspensive site attack for reading sensitive data from another site.The AJAX call will return the error message:
No ‘Access-Control-Allow-Origin’ header is present on the requested resource
But so many times we are using multipe domain applications which is reqired to call from one domain to other domain; in this case we need to allow cross origin policy.
Then in this case if the browser supports CORS, it sets the headers automatically for cross-origin requests."
If all the things will work as expected with the server, then the server adds "Access-Control-Allow-Origin" header in the response.
When the response is not included in the header Access-Control-Allow-Origin, then this kind of request will be fail.
Same origin vs Different origin
Two URLs have the same origin if both belong to the same domain.
These two URLs have the same origin,
https://test.com/index.html
https://test.com/about.html
The following URLs have different origins than the previous two URLs,
https://hello.net
https://www.hello.com/foo.html
CORS Setup
To se tup the CORS we need to go with the following steps
Install Nuget package: Microsoft.AspNetCore.Cors.
For the installation we have 2 way to do it.
Using package manager,
PM> Install-package Microsoft.AspNetCore.Cors
Using application Nuget search.
After nuget package is installed you will be able to see it in your application package library.
Configure CORS startup class inside the ConfigureService method.
- public void ConfigureServices(IServiceCollection services)
- services.AddCors(options =>
- {
- options.AddPolicy("Policy11",
- builder => builder.WithOrigins("http://hello.com"));
- });
Enable CORS using middleware in the Configure method.
- public void Configure(IApplicationBuilder app)
- {
- app.UseCors("AllowMyOrigin");
- }
Note
We must use UseCors before the UseMvc call then only the CORS middleware will execute before any other endpoints.
Implementation
To enable CORS there are three ways to do so:
- Middleware using a named policy or default policy.
- Using endpoint routing.
- Using [EnableCors] attribute.
Note
When you use UseCors and UseResponseCaching both, then UseCors must be called before UseResponseCaching.
Middleware uses a named policy or default policy.
This following code enables the default CORS policy,
- public class Startup {
- public void ConfigureServices(IServiceCollection services) {
- services.AddCors(options => {
- options.AddDefaultPolicy(builder => {
- builder.WithOrigins("http://hello.com", "http://www.test.com");
- });
- });
- services.AddControllers();
- }
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
- if (env.IsDevelopment()) {
- app.UseDeveloperExceptionPage();
- }
- app.UseRouting();
- app.UseCors();
- app.UseEndpoints(endpoints => {
- endpoints.MapControllers();
- });
- }
- }
The above code applies the default CORS policy to all controllers.
Using endpoint routing.
Using endpoint routing, CORS can be apply per-endpoint basis using the RequireCors.
- public class Startup {
- readonly string allowCors = "_myOrigins";
- public void ConfigureServices(IServiceCollection services) {
- services.AddCors(options => {
- options.AddPolicy(name: allowCors, builder => {
- builder.WithOrigins("http://hello.com");
- });
- });
- }
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
- if (env.IsDevelopment()) {
- app.UseDeveloperExceptionPage();
- }
- app.UseRouting();
- app.UseCors();
- app.UseAuthorization();
- app.UseEndpoints(endpoints => {
- endpoints.MapGet("/foo", context => context.Response.WriteAsync("foo")).RequireCors(MyAllowSpecificOrigins);
- });
- }
- }
Using [EnableCors] attribute.
Sometimes we need to allow CORS for spcific end points.
This [EnableCors] attribute allow CORS for selected endpoints, so it will not impact the all endpoints,
This attribute will be applied on the following places:
- Global
- Controller
- action method
Example
Action Level
- public class TestController: ControllerBase {
- [EnableCors("Policy2")]
- [HttpGet]
- public ActionResult < IEnumerable < string >> Get() {
- return new string[] {
- "apple",
- "mango"
- };
- }
- [EnableCors("Policy1")]
- [HttpGet("{id}")]
- public ActionResult < string > Get(int id) {
- return "test"
- }
Controller Level
To apply the CORS policy for a particular controller we need to add the [EnableCors] attribute at controller level.
- [EnableCors("Policy1")]
- public class HomeController : Controller
- {
- }
Global level
You can enable CORS globally for all controllers by adding the CorsAuthorizationFilterFactory filter in the ConfigureServices method,
- public void ConfigureServices(IServiceCollection services) {
- services.AddMvc();
- services.Configure < MvcOptions > (options => {
- options.Filters.Add(new CorsAuthorizationFilterFactory("Policy1"));
- });
- }
Note
The CORS order of execution is: action, controller, global. Action-level policies execute over controller-level policies, and controller-level policies take precedence over global policies.
Disable CORS
Sometimes we need to disable CORS for a controller level or an action length, then we need to use the inbuilt provided [DisableCors] attribute.
- [DisableCors]
- public IActionResult About()
- {
- return View();
- }
CORS policy options
There are many more options availables that we can set in CORS policy,
- allowed origins
- allowed HTTP methods
- allowed request headers
- response headers
- Credentials in CORS requests
- preflight expiration time
Multiple CORS
Sometimes we need to add multiple CORS.
The following code will create two CORS policies:
- public void ConfigureServices(IServiceCollection services) {
- services.AddCors(options => {
- options.AddPolicy("Policy1", builder => {
- builder.WithOrigins("http://hello.com");
- });
- options.AddPolicy("Policy2", builder => {
- builder.WithOrigins("http://www.test.com").AllowAnyHeader().AllowAnyMethod();
- });
- });
Thank you for taking your valuable time to read the full article.