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

前端 未结 6 1152
孤城傲影
孤城傲影 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:35

    Create a custom AuthorizeAttribute:

    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized");
        }
    }
    

    If you in the future skip the web.config stuff and use owin to setup your authentication, you could in your Startup.cs do:

    var provider = new CookieAuthenticationProvider();
    var originalHandler = provider.OnApplyRedirect;
    provider.OnApplyRedirect = context =>
    {
        if (!context.Request.Uri.LocalPath.StartsWith(VirtualPathUtility.ToAbsolute("~/api")))
        {
            context.RedirectUri = new Uri(context.RedirectUri).PathAndQuery;
            originalHandler.Invoke(context);
        }
    };
    
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        CookieName = FormsAuthentication.FormsCookieName,
        LoginPath = new PathString("/Account/LogOn"),
        ExpireTimeSpan = TimeSpan.FromMinutes(240),
        Provider = provider
    });
    

提交回复
热议问题