Reputation: 1169
I am trying to set up a react front end to talk to a .net back end. However I seem to be stuck on cors set up. Below I have my startup code from the back end project as well as the code from my front end. I've followed multiple guides and I am not sure where I am messing up, this worked on my localhost previously but not when deployed to cloud. (guides I am following: https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1 and https://code-maze.com/enabling-cors-in-asp-net-core/)
Thanks for the help!
Error from React App console: Access to fetch at 'https://backend.azurewebsites.net/api/accountcredentials' from origin 'https://frontend.azurewebsites.net' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Startup code in asp.net project:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddNewtonsoftJson();
services.AddSingleton<UserService>();
services.AddSingleton<AccountService>();
services.AddCors(o => o.AddPolicy("ReactPolicy", builder =>
{
builder.AllowAnyOrigin() //dev
//.WithOrigins("http://localhost:3007") // dev
//.WithOrigins("https://frontend.azurewebsites.net")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
}));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting(routes =>
{
routes.MapControllers();
});
app.UseCors("ReactPolicy");
app.UseAuthorization();
}
Attributes on controller class:
[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
[EnableCors("ReactPolicy")]
Upvotes: 4
Views: 4973
Reputation: 1985
try this way :
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public void ConfigureServices(IServiceCollection services)
{
...
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.SetIsOriginAllowed(isOriginAllowed: _ => true).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
});
});
...
}
public void Configure(IApplicationBuilder app, IHostEnvironment env)
{
...
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
app.UseCors(MyAllowSpecificOrigins);
...
}
edit MyAllowSpecificOrigins
to your cors name
Upvotes: 6