ASP.NET core Web API Authorize Attribute return 404 Error & force redirect
maybe you have to add the AddAuthentication line after the AddControllers() line
Is it possible that DefaultChallengeScheme is redirecting to a page that does not exist such as a login page when it encounters the authorize attribute which could cause the 404?
Try setting the default challenge to the Jwt schema which returns not authorized.
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddIdentityServerAuthentication(options =>
{
options.Authority = "http://localhost:60415";
options.ApiName = "mCareApi";
options.RequireHttpsMetadata = false;
});
Or you could try the method I mentioned in the article below by providing a handler for the event.
services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
.AddIdentityServerAuthentication(options =>
{
options.JwtBearerEvents = new JwtBearerEvents
{
OnChallenge = context =>
{
context.Response.StatusCode = 401;
return Task.CompletedTask;
}
};
options.Authority = "http://localhost:60415";
options.ApiName = "mCareApi";
options.RequireHttpsMetadata = false;
});