Make Web API authentication return 401 instead of redirect to login page

前端 未结 6 1157
孤城傲影
孤城傲影 2021-01-04 00:58

I have Web API with OWIN Authentication in Web MVC. I\'m using in Web.Config for my Web MVC so it\'s redirecting to login page.



        
6条回答
  •  轮回少年
    2021-01-04 01:15

    I struggled with this issue and I came up with a way to only do the redirect if I didn't find the token that I use in the header for my custom manual authorization of my WebApi. This is my setup (notice the Provider object and OnApplyRedirect action)

        app.UseCookieAuthentication(new CookieAuthenticationOptions
       {
         AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
         LoginPath = new PathString("/Account/Login"),
         ExpireTimeSpan = TimeSpan.FromMinutes(30),
         Provider =  new CookieAuthenticationProvider
          {
            OnApplyRedirect = (ctx) => {
                var token = HttpContext.Current.Request.Headers.Get("X-User-Token");
                if (token == null) ctx.Response.Redirect(ctx.RedirectUri);
             }
          }
       });  
    

提交回复
热议问题