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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) | |
.AddCookie(options => | |
{ | |
options.LoginPath = new PathString("/Account/Login/"); | |
options.Events.OnRedirectToLogin = (ctx) => | |
{ | |
if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200) | |
ctx.Response.StatusCode = 401; | |
else | |
ctx.Response.Redirect(ctx.RedirectUri); | |
return Task.CompletedTask; | |
}; | |
}); |