ASP.Net Core - no redirect on API auth error

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

    I just use Barry Dorrans Asp Net Authorization Workshop

    in ConfigureServices I just add services.AddAuthorization();.

    and in Configure add this code:

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationScheme = "Cookie",
        LoginPath = new PathString("/Account/Login/"),
        AccessDeniedPath = new PathString("/Account/Forbidden/"),
        AutomaticAuthenticate = true,
        AutomaticChallenge = true,
        Events = new CookieAuthenticationEvents()
        {
            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;
            },
            OnRedirectToAccessDenied = (ctx) =>
            {
                if (ctx.Request.Path.StartsWithSegments("/api") && ctx.Response.StatusCode == 200)
                {
                    ctx.Response.StatusCode = 403;
                }
                else
                {
                    ctx.Response.Redirect(ctx.RedirectUri);
                }
                return Task.CompletedTask;
            }
        }
    }
    

    In Mvc reroute to Account/Login?ReturnUrl=[...] and in API you will get 401 or 403.

提交回复
热议问题