DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Enhanced API Security: Fine-Grained Access Control Using OPA and Kong Gateway
  • Obfuscation vs Encryption: How to Protect Your .NET Code the Right Way
  • Safeguarding Web Applications With Cloud Service Providers: Anti-CSRF Tokenization Best Practices
  • The Future of Rollouts: From Big Bang to Smart and Secure Approach to Web Application Deployments

Trending

  • Teradata Performance and Skew Prevention Tips
  • A Guide to Container Runtimes
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Contextual AI Integration for Agile Product Teams
  1. DZone
  2. Coding
  3. Languages
  4. CORS in .NET Core: .NET Core Security Part VI

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

A developer gives a tutorial on how to enable CORS in your .NET Core web application. Read on for some Rocky Mountain cold CORS app sec.

By 
Neel Bhatt user avatar
Neel Bhatt
·
Apr. 30, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
145.0K Views

Join the DZone community and get the full member experience.

Join For Free

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

In this post, we will look at CORS and how to enable CORS in your .NET Core application.

What Is CORS?

Before going into the basic question "What is CORS?", let us imagine a scenario related to that.

Let us start with a very basic example.

Suppose there are two URLs like the ones below:

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

The above URLs look almost identical, so let us call them, "same origin."

Now, after making a little twist, we have some more URLs, as shown below:

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

So, since the URLs in the above example do not look similar, we'll use the term "Different origin" to describe them.

If the CORS is not enabled you might get an exception like the one below 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 our APIs?

We have a savior here: CORS!

Now the question is, "What is CORS?"

CORS stands for Cross-Origin Resource Sharing.

Per the ASP.NET Core docs, "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."

Simply put - CORS gives you the power to allow cross-domain calls from the specified domains.

How Does CORS Work?

  • Once we use CORS, new HTTP headers are introduced which enable 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 that contains the origin header which includes the domain information.
  • If everything goes well with the server, the server adds an Access-Control-Allow-Origin header in the response.
  • The value of the header, Access-Control-Allow-Origin, could be * in case any origin should be allowed or for when we want to allow any specific domain in the name of the 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.

Coming to .NET Core: Does .NET Core Support CORS?

Yes, it surely does.

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

You just need to follow below steps:

  • Install the Microsoft.AspNetCore.Cors Nuget package.
  • Configure CORS in the ConfigureService method.
  • Enable CORS using middleware in the Configure method.
  • Enable CORS in .NET Core MVC by enabling it in 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:

Configure CORS

First of all, we will add a CORS service in the Startup.cs file as shown 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 the WithOrigins method which allows only specific origins to make requests.

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

  • 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 the Startup.cs class. By doing this, we are enabling CORS for the entire application.

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

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

Apply CORS in a .NET Core Application

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

For that, there are mainly 3 options, which we'll go over below. 

Use This in Your Attribute on the Controller's Action

Add an [EnableCors] attribute above the specific action method:

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

Use This in Your Attribute on the Controller

Add an [EnableCors] attribute above the specific Controller:

[EnableCors("AllowMyOrigin")]

public class ValuesController : Controller

Apply CORS Globally

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

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

That's all for today, I hope this post helps!

.NET security Requests

Published at DZone with permission of Neel Bhatt, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Enhanced API Security: Fine-Grained Access Control Using OPA and Kong Gateway
  • Obfuscation vs Encryption: How to Protect Your .NET Code the Right Way
  • Safeguarding Web Applications With Cloud Service Providers: Anti-CSRF Tokenization Best Practices
  • The Future of Rollouts: From Big Bang to Smart and Secure Approach to Web Application Deployments

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!