In my ASP.NET Core project I got a few API-Controllers with jwt-authorization like this:
[Route(\"api/v1/[controller]\")]
public class MyController : Controller
Microsoft's web api stack is set up to do this out-of-the-box. The solution is at the client end.
Add this header to the client request:
'X-Requested-With': 'XMLHttpRequest'
Web api looks for that header. When present it returns a 401 if the request is unauthenticated. When the header is absent it returns the redirect to the login page.
See this https://github.com/aspnet/Security/issues/1394#issuecomment-326445124
I think you only need the more complex code in the cookie events if you cannot modify the client.