Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
ngajugodwin opened this issue Oct 15, 2021 · 13 comments
Closed

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

ngajugodwin opened this issue Oct 15, 2021 · 13 comments

Comments

@ngajugodwin
Copy link

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.

@ngajugodwin ngajugodwin changed the title Enabling CORS - How To Fix Cors Policy Issue Question: Enabling CORS - How To Fix Cors Policy Issue? Oct 16, 2021
@iayti
Copy link
Contributor

iayti commented Oct 16, 2021

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
Copy link
Author

ngajugodwin commented Oct 16, 2021

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
Copy link
Contributor

ramax495 commented Oct 17, 2021

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();

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

@ngajugodwin
Copy link
Author

ngajugodwin commented Oct 17, 2021

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
Copy link
Contributor

I see you edited your comment.

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

@ngajugodwin
Copy link
Author

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
Copy link
Contributor

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
Copy link
Author

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
Copy link
Contributor

@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: dotnet/AspNetCore.Docs#19957

@ngajugodwin
Copy link
Author

@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
Copy link
Contributor

@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
Copy link
Author

@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
Copy link
Owner

Thanks all

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants