I have setup an Identity Server 4 on a .Net 6 web app. My web UI is another web app that is configured as the client of the Identity Sever. User is correctly refered to the login page when request accessing to a secured page/api and login is done OK. The solution also has other microservices that are also configured to use IS as oidc. The problem is after a while if I do not refresh the page, authentication fails when calling webapis. When I check the request, before the main call to the webapi controller, a request to the IS is made but is refused with CORS exception. I have configured the IS web app to accept CORS like this:
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
and then:
app.UseCors("CorsPolicy");
What I am missing?
The mentioned settings did not solve the problem
>Solution :
The problem is might be caused from the expiration of the cookie or token (I’m not sure). But you should also add
builder.Services.AddSingleton<ICorsPolicyService>((container) => {
var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>();
return new DefaultCorsPolicyService(logger)
{
AllowedOrigins = { /*webUIOriginHere!NotUrl!*/ }
};
});
to the program.cs of Identity Server webapp and the problem should be solved.
Also adding AnyOrigin is dangerous. try doing something like this:
builder.Services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.WithOrigins( webUIOrigin )
.AllowAnyMethod()
.AllowAnyHeader());
});