49

I'm not sure what I'm missing, but can't seem to get my CORS Policy working with .NET Core 3.1 and Angular 8 client-side.

Startup.cs:

        public void ConfigureServices(IServiceCollection services)
        {
            // ...

            // Add CORS policy
            services.AddCors(options =>
            {
                options.AddPolicy("foo",
                builder =>
                {
                    // Not a permanent solution, but just trying to isolate the problem
                    builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
                });
            });

            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            // Use the CORS policy
            app.UseCors("foo");

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

Error Message Client-side:

Access to XMLHttpRequest at 'https://localhost:8082/api/auth/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

UPDATE:

Although I was configuring CORS incorrectly (and the accepted answer below did in fact help with that) the root of issue was unrelated. For additional context, the app was working completely fine when running the API and Angular app using the CLI - I was only having this issue after deploying them both to a web server.

The "actual" issue ended up being related to the SQL connection, which I only discovered after adding flat-file error logging to the API and running a SQL Server trace to find that the app wasn't able to connect to SQL at all.

I would normally expect this to just return a 500 and I would have realized the issue in a matter of 10 seconds - however the CORS mis-configuration meant a 500 was never actually being returned because the CORS middleware failed first. This was immensely frustrating to say the absolute least! . However I want to add that here in case others find themselves in this situation, as I was "chasing the wrong rabbit," if you will. After fixing the CORS configuration, I realized the actual issue was entirely unrelated to CORS.

TL;DR; - Sometimes "Non-CORS" .NET Server-side Errors Can Be Returned as CORS Errors If CORS policies Aren't Set Correctly

References:

https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware

https://medium.com/swlh/cors-headers-with-dot-net-core-3-5c9dfc664785

Kurtis Jungersen
  • 2,204
  • 1
  • 26
  • 31
  • 1
    try to set `app.UseCors("foo");` before `app.UseHttpsRedirection();` – StepUp Dec 13 '19 at 07:20
  • @StepUp thanks for the recommendation, but still no luck – Kurtis Jungersen Dec 13 '19 at 07:28
  • Have you solved your problem? – StepUp Dec 17 '19 at 15:03
  • Have anyone solved this issue? Why no answer is accepted? – Waseem Ahmad Naeem Jan 31 '20 at 11:38
  • Yes, sorry I never circled back to this issue after resolving it. I've added an update to the question with some additional context. Thank you! – Kurtis Jungersen Feb 04 '20 at 20:00
  • I am getting this same issue even trying to return a BadRequest("Reason here..") incredibly frustrating. Cors configured correctly, with no app.UseHttpsRedirection(); Unfortunately, my app works just great locally, but cors blows up once deployed. – Connor Feb 28 '20 at 01:05
  • It's frustrating indeed! Any luck with flat-file error logging? In my situation that's what helped me track down the "real" issue. – Kurtis Jungersen Feb 28 '20 at 14:51
  • 2
    My CORS was setup correctly for .net core 3.1 and I was getting CORS errors. Similarly to what OP found, there was actually an issue with a service I was trying to inject into my controller, which God-knows-why was throwing a CORS error instead of a meaningful one – TabsNotSpaces Oct 01 '20 at 19:08
  • I tried all of everythings until use https both of request and response in ip. use https. – mustafatorun Dec 07 '20 at 08:02
  • Worth noting that in Chrome the preflight OPTIONS request isn't shown in the Dev Tools (by default), which can make troubleshooting harder. Use Firefox (or probably there's some config flag to make Chrome show it), then you can see what CORS headers are being returned, if any. – Rory Feb 21 '21 at 12:53

12 Answers12

39

first app.UseRouting(); then app.UseCors("foo");

Change your Configure method like the following :

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();



    app.UseRouting();  // first
    // Use the CORS policy
    app.UseCors("foo"); // second

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

It worked for me !

Abolfazl Roshanzamir
  • 12,730
  • 5
  • 63
  • 79
  • -is there a nuget package necessary? – chana Dec 16 '19 at 11:32
  • nuget package for cors – chana Dec 16 '19 at 15:45
  • 2
    @chana - you do not need to install nuget package – Abolfazl Roshanzamir Dec 16 '19 at 17:35
  • 12
    I was stuck on this issue for DAYS! nothing from the internet worked. Your solution combined with OP's `ConfigureServices` code solved my problem. Thanks a lot! – Tahreem Iqbal Dec 28 '19 at 08:02
  • 1
    Is it documented anywhere ? – Joy Feb 09 '20 at 07:00
  • 1
    Was going rounds & rounds on this issue, please keep an eye on the version number especially when dealing with security packs, if one has searched for web API CORS and lost with many results like me, Installing packages Microsoft.WebApi.Cors Owin.Cors like in other answers absolutely not required in .Net Core 3 which already bundled, never expected order matters till I came across this answer which is surprising to me. Thanks a lot for this answer, this fix could have gone for ever.. – Naga Nov 01 '20 at 19:17
33

Web API is using app.UseHttpsRedirection(); which cause CORS issue if requesting client is not https based. So in order to use it with http client we need to comment or remove that line.

This issue is not with CORS, the https is causing this issue but thrown error is saying its with CORS.

Waseem Ahmad Naeem
  • 850
  • 1
  • 10
  • 22
  • 8
    That is correct! the line UseHttpsRedirection() must be after UseCors() – Eric Mar 23 '20 at 13:04
  • 2
    Removing it helps. But replacing UseHttpsRedirection() does not work for me. I placed it after UseCors. And UseCors is placed after userouting and before UseHttpsRedirection. – M Yil Nov 25 '20 at 13:50
  • 1
    This was the issue for me as well. It's the 2nd time I've been stuck trying to find a solution for CORS issue, when in fact it's something else causing it. – Eternal21 May 13 '22 at 15:58
8

When adding the Cors Service make sure to include .SetIsOriginAllowed((host) => true) after .WithOrigins("http://localhost:4200")

services.AddCors(options => {
            options.AddPolicy("mypolicy",builder => builder
            .WithOrigins("http://localhost:4200/")
            .SetIsOriginAllowed((host) => true)
            .AllowAnyMethod()
            .AllowAnyHeader());
  });
  • 1
    Works for me (without the spare bracket) but I wish I knew why. – itsLex Sep 24 '20 at 18:25
  • 1
    This implementation is not completely safe. Ideally, around `.WithOrigins` and `.SetOriginIsOriginAllowed` call should look more like: `.WithOrigins("http://localhost:4200") //note the lack of end /` `.SetIsOriginAllowed((host)=>"http://localhost:4200".Equals(host,StringComparison.InvariantCultureIgnoreCase))` to make sure that you only respond when an appropriate domain is specified – to11mtm Jan 14 '21 at 01:33
4

There might be several issues causing CORS error. Make sure to configure CORS properly first. You can configure it in the below way:

        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
        });

Then in Configure() of Startup.cs file, the following should be the order of middlewares:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }


        // Enable middleware to serve generated Swagger as a JSON endpoint.
        app.UseSwagger();

        // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
        // specifying the Swagger JSON endpoint.
        app.UseSwaggerUI(c =>
        {
            c.SwaggerEndpoint("../swagger/v1/swagger.json", "API");
        });

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("CorsPolicy");

        app.UseAuthentication();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }

If you have configured the .NET core application to run on HTTPs URL, then make sure to invoke the https URL of the application for API request from Angular as well.

If you are invoking HTTP URL from the Angular and running .NET core application on HTTPs, then remove the app.UseHttpsRedirection() middleware.

To use app.UseHttpsRedirection(), either run .NET core on HTTPs URL and make HTTPs requests from the angular or run .NET core on HTTP URL and make HTTP requests from the angular (in this case, the .NET application must only run on HTTP. It shouldn't be configured to run on both HTTP and HTTPs).

The above things will most probably solve your problem.

Sunny
  • 752
  • 1
  • 11
  • 24
2

I faced the same issue and I just found out that custom middlewares must go after the useCors()

        app.UseHttpsRedirection();

        app.UseAuthentication();

        app.UsePathBase("/api");

        app.UseRouting();

        app.UseCors("AllowSpecificOrigins");

        app.UseMiddleware<CountryMiddleware>();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
10 Rep
  • 2,217
  • 7
  • 19
  • 33
pouyada
  • 341
  • 3
  • 15
2

I had this error, I used to run my project with the CLI .net core and it did not worked but when I ran the project with IIS Express Visual studio it worked with no CORS problems, that happens for the redirection to https middleware in Configure method of Startup.css class app.UseHttpsRedirection();, like Waseem Ahmad Naeem mentioned.

Either its good to always visit the .Net Core Middleware order, putting them in bad order may bring performance problems to the applications or even make that things does not work as expected. Middleware docs below.

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-5.0

10 Rep
  • 2,217
  • 7
  • 19
  • 33
1

As you are using localhost as http://localhost:4200, then try to set it in your configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => options.AddPolicy("ApiCorsPolicy", build =>
    {                
        build.WithOrigins("http://localhost:4200")
             .AllowAnyMethod()
             .AllowAnyHeader();
        }));
        // ... other code is omitted for the brevity
     }
}

And Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider provider)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseCors("ApiCorsPolicy");
    app.UseHttpsRedirection();
    app.UseAuthentication();
    app.UseMvc();
}
StepUp
  • 36,391
  • 15
  • 88
  • 148
1

The call to UseCors must be placed after UseRouting, but before UseAuthorization. For more information, see https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1

Adetayo
  • 11
  • 2
1

In my situation it was related to the Content-Type of the header being application/json.

Only those Content-Type headers are allowed with CORS:

application/x-www-form-urlencoded

multipart/form-data

text/plain

Whistler
  • 1,897
  • 4
  • 29
  • 50
1

Things to make sure while using CORS in net core

  1. Under Configure Make sure it is added after app.UseRouting();

  2. In ConfigureServices it doesn't matter the exact location.

  3. If you are not using https then also it wont work and it complains there is a CORS issue. I have added it in the below order and it works fine.

      app.UseRouting();
    
      app.UseCors("policy");
    
      app.UseHttpsRedirection();
    
      app.UseAuthorization();
    
0

Try this util

https://www.nuget.org/packages/Microsoft.AspNetCore.Cors/ Using this you can enable/disable the cors in your .net core application

Pandiyan Cool
  • 6,381
  • 8
  • 51
  • 87
0

I resolved my issue by adding EnableCors to my controller

[EnableCors("MyPolicy")]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
jug
  • 441
  • 4
  • 10