I have this configuration in my Startup
method, apparently everything works fine
services.AddCors(options =>
{
options.AddPolicy("MyPolicy",
builder => builder.WithOrigins("https://localhost:5000",
"http://localhost:3000",
"http://localhost:3001")
.AllowAnyHeader()
.WithMethods("PUT", "GET"));
});
app.UseHttpsRedirection();
app.UseCors("MyPolicy");
app.UseRouting();
app.UseAuthorization();
But when I start to do tests with another url that is not registered, the request shows a cors error but at the same time the response is shown, so does it mean that I run my services without being registered?
In this screenshot, you can see the url to which I make a request
What is the right thing to do to secure my API? I have also read that browsers will always execute requests even if it is not visible
Thank you very much for reading me, I’m new to this
3
Answers
the dot.net code in Configure and ConfigureService is correct. try allow any method and remove with origins. see if you can hit the endpoint with postman
Firdtly,the url is
http://localhost:44344
,so you need to add it intoWithOrigins
.And you need to make sure the method type of the request is including inWithMethods("PUT", "GET")
.Also,you’d better putapp.UseCors("MyPolicy");
betweenapp.UseRouting();
andapp.UseAuthorization();
.In that case browser will always execute the request, this is how it works.
As an option apart from CORS you can add host filtering. Just add semicolon-delimited list of host names into your
appsettings.json
See documentation page for details
Also starting from ASP.NET Core 5
Kestrel
server supports host filtering as well – link