.NET Core API and CORS – allow POST from Javascript using Microsoft.AspNetCore.Cors

After hours of debugging, I finally managed to apply CORS correctly to my .NET Core 3.0 Application. Like so many other before me, I used this article as reference:

But I still managed to get it wrong so many times. CORS is not easy to set up, and even harder to test. But here is how I did it:

STEP 1: DEFINE AN ARBITRARY POLICY NAME:

Since .NET Core allows you to have several CORS policies within your API, you need to define a policy name. I will have one CORS policy for my entire API, and it’s just a string, you can name it whatever you like:

 readonly string _POLICY_NAME = "_myAllowSpecificOrigins";

STEP 2: ADD CORS TO Startup.cs – ConfigureServices(IServiceCollection services)

The Actual CORS rules are added to the ConfigureServices method:

services.AddCors(options =>
{
  options.AddPolicy(_POLICY_NAME,
  builder =>
  {
    builder.WithOrigins("https://*.test-cors.org")
	  .SetIsOriginAllowedToAllowWildcardSubdomains()
	  .AllowAnyHeader()
	  .AllowAnyMethod()
	  .AllowCredentials();
  });
});

Here I allow any subdomain from *.test-cors.org, with any header, any method and also allow credentials.

STEP 3: APPLY CORS TO Startup.cs – Configure(IApplicationBuilder app)

The CORS rules must be applied:

app.UseRouting();
// app.UseCors MUST be placed between UseRouting and UseEndpoints
app.UseCors(_POLICY_NAME); 
...
...
// Also add RequireCors to the controllers:
app.UseEndpoints(endpoints => { endpoints.MapControllers().RequireCors(_POLICY_NAME); });

REMEMBER TO ADD THE POLICY NAME TO BOTH app.UseCors AND app.UseEndpoints. This is where I failed several times.

STEP 4: TEST THE CORS SETTINGS WITH GET AND POST

Use this website to test your CORS settings:

First you test that this website can access your API. It should have access, since it has been added with builder.WithOrigins(https://*.test-cors.org), and we allow wildcard subdomains.

Set a breakpoint in a GET and a POST method, call the endpoints from http://www.test-cors.org. Remember to open the console window (F12) in the browser to see any CORS errors:

STEP 5: TEST THAT CORS BLOCKS DOMAINS FROM GET AND POST

Now go to your code and change the allowed origins, so http://www.test-cors.org is not allowed:

services.AddCors(options =>
{
  options.AddPolicy(_POLICY_NAME,
  builder =>
  {
    builder.WithOrigins("https://*.anotherdomain.org")
	  .SetIsOriginAllowedToAllowWildcardSubdomains()
	  .AllowAnyHeader()
	  .AllowAnyMethod()
	  .AllowCredentials();
  });
});

Go back to the test and try again. Add breakpoints in GET and POST methods, and call the API endpoints once again from http://www.test-cors.org.

Please notice that for GET, your breakpoint is actually hit, but the CORS settings will block the result from getting to the client. For POST, the endpoint is not hit.

In the console you will see the following error:

CORS failed

CORS failed

Access to XMLHttpRequest at ‘https://localhost:44370/api/endpoint from origin ‘https://www.test-cors.org’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

So there it is. You are now a CORS expert. Happy coding.

MORE TO READ:

 

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, .NET Core, c# and tagged , , . Bookmark the permalink.

1 Response to .NET Core API and CORS – allow POST from Javascript using Microsoft.AspNetCore.Cors

  1. Pingback: ASP.Net Core API – “‘s’ is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.” | Brian Pedersen's Sitecore and .NET Blog

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.