ASP.Net Core - no redirect on API auth error

后端 未结 3 1792
余生分开走
余生分开走 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:41

    Update ASP.NET Core 2.x

    The authorization changed a little in ASP.NET Core 2.0. The answer below ist just valid for ASP.NET Core 1.x. For ASP.NET Core 2.0 refer to this answer and this GitHub annoucement.

    ASP.NET Core 1.x

    What you seems to have forgotten is that app.UseIdentity() also registers the cookie middleware.

    var options = app.ApplicationServices.GetRequiredService>().Value;
    app.UseCookieAuthentication(options.Cookies.ExternalCookie);
    app.UseCookieAuthentication(options.Cookies.TwoFactorRememberMeCookie);
    app.UseCookieAuthentication(options.Cookies.TwoFactorUserIdCookie);
    app.UseCookieAuthentication(options.Cookies.ApplicationCookie);
    

    and the ASP.NET Core Identity sets the AutomaticChallange to true for cookie (ApplicationCookie) middleware (see source). Hence the redirect to /Account/Login?ReturnUrl. You will need do disable this option in Identity.

    services.AddIdentity(options =>
    {
        options.Cookies.ApplicationCookie.AutomaticChallenge = false;
    });
    

    If you really want have Identity's Auth (login to web page) and JWT, you'd need to register the middlewares based on the url. So i.e. app.UseIdentity() is only registered for non-api urls and Jwt middleware is only registered for urls starting with /api.

    You can do that with .MapWhen (docs).

    app.MapWhen(context => !context.Request.Path.StartsWith("/api"), branch => 
    {
        branch.UseIdentity();
    });
    

    Now branch.UseIdentity() will only be used, for URLs which don't start with /api, which usually are your MVC views where the redirect to /Account/Login is desired.

提交回复
热议问题