I have Asp.NET Core Web API application and trying to implement authorization but came across with CORS problem - my dev services and ui host on different ports of localhost.
On login page I get token and redirects to next page. At this time data requests to services start. But server responses with status 204: No Content for preflight request... Although, preflight response returns Access-Control-Allow-Origin: * ...
The Startup.cs looks like:
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddCors(options =>
{
options.AddPolicy("Policy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader() );
});
services.AddAuthorization();
services.AddMvc() // ...
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("Policy");
app.UseMvc();
}
Do I miss something on server side? (on client side angular's interceptor just adds Authorization header with token)
P.S. I use VS Code on OSX for developing (although it's not important as I guess)
UPDATE:
as @tpeczek adviced, I've change cors configuration to:
options.AddPolicy("Policy",
builder => builder.WithOrigins("http://localhost:80", "http://localhost")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials() );
but can't get rid of error
UPDATE 2:
The error I get is
XMLHttpRequest cannot load localhost:5000/api/<method-name>;. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost'; is therefore not allowed access. The response had HTTP status code 500.
But once I remove [Authorize]
attribute from controller it works fine. So the problem is in token checking?
UPDATE 3: The problem was in accidentally removed functionality :- ( Works now
The 204 NO CONTENT
status code is perfectly valid for CORS preflight response (see here).
Your problem results from fact that you request contains Authorization
header which makes it a "credentialed request". In such case you can't use wildcard for Access-Control-Allow-Origin
and you must specify Access-Control-Allow-Credentials
(you can read more here)
services.AddCors(options =>
{
options.AddPolicy("Policy", builder => builder
.WithOrigins("<Origin One>", "<Origin Two>", ...)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With