ASP.Net Core - no redirect on API auth error

后端 未结 3 1740
余生分开走
余生分开走 2021-02-12 19:57

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
         


        
3条回答
  •  花落未央
    2021-02-12 20:30

    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.

提交回复
热议问题