Search code examples
angularssl.net-corecorsapigee

Access to XMLHttpRequest has been blocked by CORS policy in https redirect unless I clean browser


I have an angular + .net core 2.1 application. It works well when just use http, now I want to redirect to https. However every time I got the error when I started the application to login

Access to XMLHttpRequest at ’https://appgee.mycompany.com:5001/’ from origin ’https://app.mysite.com:5001’ has been blocked by CORS policy: The ‘Access-Control-Allow-Origin’ header has a value ’https://app.mysite.com:5001’ that is not equal to the supplied origin

If I clean the browser data, then the error is gone. But it is inconvenient to user. My code in .net core:

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




app.UseHttpsRedirection();

I use apigee to do authentication, in angular I set the request header for api request for apigee as(in interceptor):

SetHeaders: {
   Authorization: 'Bearer $ {token.access_token}',
   'Access-Control-Allow-Origin': '*',
   

You see that I already allow origin both in front side and back end. But why it happens?

UPDATE:

Apigee target endpoint I have

<HTTPTargetConnection>
     <Properties/>
     <URL>http://app.mysite.com:5001</URL>
</HTTPTargetConnection>

Solution

  • app.UseCors("CorsPolicy");
    

    According to the discussion from https://weblog.west-wind.com/posts/2016/sep/26/aspnet-core-and-cors-gotchas

    @Kristian - the middleware order definitely matters, although you may be right that it has the important order is in the Configure() method, not ConfigureServices(). To be safe I make sure I have the CORS definition before MVC in both places. Checking now to see which one actually matters, or not at all. Several references mention this explicitly.

    So I put UseCors in the first line of the methods.