I’m building a backend using microsoft technologies for the first time and I’m having trouble getting my back-end to communicate with my front-end (React). The HTTP requests coming from Postman are succesful, so I doubt it is a problem with the build. I’ve been following tutorials and solutions on Stackoverflow, but I’m still getting the following message:
CORS blocking error in the console
Here is my Program.cs file, if it can help someone find the problem in my configuration:
var myAllowSpecificOrigins = "_myAllowSpecificOrigins";
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var Configuration = builder.Configuration;
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<BlogContext>(options =>
{
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});
builder.Services.AddCors(options =>
{
options.AddPolicy(name: myAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:3000")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
}
);
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(Configuration.GetValue<string>("JWTSecretKey"))
)
};
});
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddSingleton<IAuthService>(
new AuthService(
Configuration.GetValue<string>("JWTSecretKey"),
Configuration.GetValue<int>("JWTLifespan")
)
);
builder.Services
.AddMvc().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
var app = builder.Build();
app.UseCors(myAllowSpecificOrigins);
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
EDIT
I tried to allow all origins and got the following error (this is by calling localhost:5090 from client. With localhost:7090 the backend simply throw a network connection error.
Access to XMLHttpRequest at ‘http://localhost:5090/api/auth/login’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: Redirect is not allowed for a preflight request.
2
Answers
I finally solved the issue by following the recent doc from Microsoft on the subject (published 06/03/2022) and making a small tweak. It was a really simple solution and I hope it can help others in the future who have tried everything else :
https://learn.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0
I made three changes that made all the difference:
1. Remove this line of code in Program.cs: app.UseHttpsRedirection();
2. Change
with
3. Add those two lines of code before app.UseCors:
It could potentially be a missing proxy setting on the front end. Without knowing how your front end is configured, it would be my guess. Please see here for instructions on how to set it up.
In my experience, I had to configure the setting manually through a setupProxy.js file (the instructions are also included in the link above)