jasontaylordev / CleanArchitecture

Clean Architecture Solution Template for ASP.NET Core
MIT License
17k stars 3.64k forks source link

Question: Enabling CORS - How To Fix Cors Policy Issue? #467

Closed ngajugodwin closed 3 years ago

ngajugodwin commented 3 years ago

Hello,

How do I enable CORS. I'm currently trying to connect my Angular to the backEnd but still hitting the CORS policy issue.

I currently have the below code under ConfigureService() method in the startup file.

services.AddCors(opt => { opt.AddPolicy("CorsPolicy", policy => { policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:4200").Build(); }); });

And the below code under Configure() on same startup file.

app.UseCors("CorsPolicy");

Even after doing this, I still run into CORS policy issue.

Please, am I missing out something?

Appreciate any help.

iayti commented 3 years ago

Hi,

I hope the following settings will help you.

ConfigureServices: services.AddCors();

Configure: these settings must be between routing and authentication. app.UseRouting();

app.UseCors(x => x .AllowAnyMethod() .AllowAnyHeader() .SetIsOriginAllowed(origin => true) // allow any origin .AllowCredentials()); // allow credentials

app.UseAuthentication(); app.UseAuthorization();

Have a nice coding 😊

ngajugodwin commented 3 years ago

Hello @iayti,

Thanks for the input.

So I just did exact same thing but the issue still persist with the CORS policy issue when using a new Angular front end. But i'm able to access the end points with Postman.

Please see below the configure method;

image

And the Cors policy issue error;

image

Any other idea on how to fix will be appreciated.

Thanks

ramax495 commented 3 years ago

Try these variants:

  1. Add default policy in ConfigureServices:

    services.AddCors(options =>
    {
    options.AddDefaultPolicy(
        builder =>
        {
            builder
            .AllowAnyMethod()
            .AllowAnyHeader()
            .SetIsOriginAllowed(origin => true) // = any origin
            .AllowCredentials();
        });
    });

    In Configure app.UseCors();

  2. Also try to move app.UseHttpsRedirection(); after app.UseCors();

ngajugodwin commented 3 years ago

Hello @ramax495 ,

Thanks alot for the help. I see you edited your comment. The initial solution fix the issue.

See below changes i made;

  1. Add default policy in ConfigureServices:
  services.AddCors(options =>
              {
                  options.AddPolicy("CorsPolicy",
                    builder =>
                    {
                        builder
                          .AllowAnyMethod()
                          .AllowAnyHeader()
                         .SetIsOriginAllowed(origin => true) // = any origin
                          .AllowCredentials();
                    });
              });
  1. In Configure:

app.UseCors(); app.UseHttpsRedirection()

Then, the last code did the trick in Configure as well;

app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
                  endpoints.MapControllers().RequireCors("CorsPolicy");
            });

Once again, thanks!

ramax495 commented 3 years ago

I see you edited your comment.

I think the key is app.UseCors(); app.UseHttpsRedirection(); 😊

ngajugodwin commented 3 years ago

Yea, changing the location of app.UseHttpsRedirection(); also helped too.

But i noticed that if i didnt put endpoints.MapControllers().RequireCors("CorsPolicy"); it doesnt work as well. The default in there was initially endpoints.MapRazorPages();. So i had to change that as well :)

ramax495 commented 3 years ago

But i noticed that if i didnt put endpoints.MapControllers().RequireCors("CorsPolicy");

It's optional way.

In one case you add your configured named policy in app.UseCors("CorsPolicy"); and it applies to all endpoints by default.

In other case you add your named policy manually to each endpoint using .RequireCors("CorsPolicy"); and call app.UseCors(); without any arguments (it's more flexible way if you need).

In one more case you can just configure default policy using AddDefaultPolicy and also call app.UseCors(); without any arguments.

But all in all nothing of this works if you call UseHttpsRedirection before UseCors 😊

ngajugodwin commented 3 years ago

Thanks alot for the explanation.

I just looked at my previous project and I noticed I commented UseHttpsRedirection out. Really don't know why I did that then.

Mind to explain briefly why we call UseHttpsRedirection after UseCors?

ramax495 commented 3 years ago

@ngajugodwin Soryy, but I dont't know the reason. It's very strange but MS documentation allows calling UseHttpsRedirection before UseCors: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0#cors-with-named-policy-and-middleware-1

There is related issue in dotnet repo: https://github.com/dotnet/AspNetCore.Docs/issues/19957

ngajugodwin commented 3 years ago

@ramax495

Interestingly this is a known issue already.

Now you mention it on their repo, hopefully MS look into the issue because this can sometime be confusing.

ramax495 commented 3 years ago

@ngajugodwin I've found a short explanation: This issue is not with CORS, the https is causing this issue but thrown error is saying its with CORS. https://stackoverflow.com/a/60053610/10886266

ngajugodwin commented 3 years ago

@ramax495

Thanks. I'll just read through just now.

Waseem explanation did the justice. Now I understand what is going on behind the scene.

Much appreciated for the pointed and your time.

jasontaylordev commented 3 years ago

Thanks all