Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with CORS Policy and .NET Core 3.1

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

like image 329
Kurtis Jungersen Avatar asked Dec 13 '19 07:12

Kurtis Jungersen


People also ask

How do I fix a CORS policy issue?

Cross-Origin Resource Sharing (CORS) errors occur when a server doesn't return the HTTP headers required by the CORS standard. To resolve a CORS error from an API Gateway REST API or HTTP API, you must reconfigure the API to meet the CORS standard.

What is CORS policy in .NET core?

CORS means cross-origin resource sharing. You'll see more in just a minute, but in a nutshell, CORS is a mechanism—an HTTP protocol, to be exact—that allows web applications to access resources hosted on different domains (or origins.)


4 Answers

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 !

like image 140
AbolfazlR Avatar answered Oct 17 '22 21:10

AbolfazlR


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.

like image 32
Waseem Ahmad Naeem Avatar answered Oct 17 '22 22:10

Waseem Ahmad Naeem


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());
  });
like image 7
Sean Baraka Avatar answered Oct 17 '22 22:10

Sean Baraka


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.

like image 4
Sunny Avatar answered Oct 17 '22 21:10

Sunny