CORS policy . net core and angular 8

Asked

Viewed 90 times

1

I’m having problems with CORS policy. I pulbligated a site on IIS and did not put host name (accessed by IP). When I put the host name (www.nome-do-site.com) the system stopped working and the problem was:

Access to Xmlhttprequest at 'http://back' from origin 'http://front' has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested Resource.

In the backend, Startup.Cs is coded like this in the Configuraeservices method:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddCors(o => o.AddPolicy("MyPolicy",
            builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
                .Build())
        );
        services.AddMvcCore(options => { options.RespectBrowserAcceptHeader = true; }).AddJsonFormatters(); 
        services.AddSingleton(_ => Configuration);
        services.AddAutoMapper();
        services
            .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.RequireHttpsMetadata = !_iHostingEnvironment.IsDevelopment();
                options.SaveToken = true;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidateAudience = true,
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer = Configuration["Jwt:Issuer"],
                    ValidAudience = Configuration["Jwt:Issuer"],
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
                };
            });

        services.Configure<IISServerOptions>(options =>
        {
            options.AutomaticAuthentication = false;
        });

        DomainServices(services);
        Repositories(services);
        Factory(services);
        ExternalService(services);
    }

And so in the Configure method

public void Configure(IApplicationBuilder app)
    {
        if (_iHostingEnvironment.IsDevelopment())
            app.UseDeveloperExceptionPage();
        else
            app.UseHsts();

        app.UseCors("MyPolicy");
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseAuthentication();
        app.UseMvc(routes => routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}")
        );
    }

And yet you’re giving me this CORS problem. Remembering before changing from "http://localhost/login" to "http://www.nome-do-site.com/login" did not have this problem.

1 answer

0

There are many things that can cause this type of error related to Cors. Put your complete Configure and Configure method to analyze. What I can say is that the settings must have an order according to official documentation.

In Configuraeservices, you must add Cors before the Controllers.

 services.addCors();
 services.addControllers();

In Configure, you usually set redirects, Routes and then Cors.

 app.UseHttpsRedirection(); //se existir, tente tirar pois o seu erro nao ta pedindo https
 app.UseRouting();
 app.UseCors();

EDIT:

Try changing your code like this:

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


 
    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseCors("MyPolicy");


    app.UseAuthentication();
    app.UseMvc(routes => routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}")
    );
  • I put the complete code of the two methods, what do you think?

  • Sorry for the delay, but the call to the app.Usecors should come after Usehttpsredirection

Browser other questions tagged

You are not signed in. Login or sign up in order to post.