I use ASP.NET Core for an api and can not find a way to configure identity to return a 401 instead of redirecting to the login page. I use the IdentityServerAuthentication Middleware.
In the Startup.cs, I give these options:
var options = new IdentityServerAuthenticationOptions
{
Authority = Configuration.GetConnectionString("Authority"),
ScopeName = "scopeName",
RequireHttpsMetadata = false,
};
app.UseIdentityServerAuthentication(options);
I find a solution, In the request, you can add a header X-Requested-With with a value of XMLHttpRequest. This will tell identity to not redirect to the login page.