My ASP .Net Core 2.2 web application has some controllers that return View(s) and some controllers that return a json result as they are just API controllers.
My website uses cookie authentication, with this declaration:
services
.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.AccessDeniedPath = "/Pages/AccessDenied";
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.Cookie.SameSite = SameSiteMode.Strict;
});
In the Configuration section:
// ...
app.UseAuthentication();
app.UseDefaultFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Pages}/{action=Index}/{id?}");
});
My PagesController just inherits from Microsoft.AspNetCore.Mvc.Controller and for some pages I put [Authorize] attribute. When a non authorized user tries to open the page it gets correcly redirected to my public AccessDenied page. Everything's good.
BUT, I have also an ApiController, which inherits from Microsoft.AspNetCore.Mvc.ControllerBase, has an attribute [ApiController] and also a [Authorize(Roles = "Administrator")]. I use this controller to communicate with javascript in my pages. The problem is that when a non authorized user tries to invoke the methods on this controller, I don't want it to respond with a HTTP 200 page (the AccessDenied one), but I want that it returns just an HTTP 401 Unauthorized because it is an API.
How can I achieve such a different behavior keeping the cookie authentication?
Thanks!