im getting this error.
Access to fetch at 'API_URL' from origin 'LOCALHOST_OR_HEROKU_URL' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
i have followed the documentation to order my Middleware, and include whats necessary from this documentation. Here is my Program.cs file.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "CORSPolicy",
policy =>
{
policy.AllowAnyOrigin();
policy.AllowAnyMethod();
policy.AllowAnyHeader();
});
});
builder.Services.AddControllers();
builder.Services
.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = false,
ValidateAudience = false,
ValidateLifetime = true,
};
});
// i have registered my services here
builder.Services.AddEndpointsApiExplorer();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors("CORSPolicy");
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute("default", "{controller=values}/{action=get} /{id?}");
});
app.MapControllers();
app.Run();
but im still getting that error from client side, and i dont know what im doing wrong.. please any help is appreciated. With thanks
2
Answers
Make sure your client application calling the Web API has the correct url with https://scheme.
So localhost:6700/api should be called as https://localhost:6700/api.
Please check and confirm 🙂
Error message clear says what is wrong here.
This one requirement is well described in MDN article (Requests with credentials part).
Credentialed requests are requests that contain any cookie data (
Cookie
header) or any data inAuthorization
header.So, highly likely solution would be replacing this line:
by setting explicit origin allowed.