In one of my ASP.NET Core applications I have Cookie authentication enabled.
When a user tries to access a controller and is not authorized, they are redirect to Account/Login?ReturnUrl=[...]. This is great for MVC endpoints but doesn’t make much sense for API requests.
There are multiple ways to avoid this from happening. The way I solved it is by checking the incoming request in the CookieAuthenticationEvents. When the request starts with ‘/API’, we return a 401 status code instead of redirecting the user: