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.
Do not put greetings, greetings, thanks,... in questions or answers. Take our [Tour].
– Augusto Vasques