Mar 25, 2014

Preventing 302 redirect for ASP.NET WebApi 2 on 401 response

If you are adding asp.net WebApi inside asp.net MVC web site you probably want to respond unauthorized to some requests. But then ASP.NET infrastructure come into play and when you try to set response status code to HttpStatusCode.Unauthorized you will get 302 redirect to login page.

If you are using asp.net identity and owin based authentication here a code that can help to solve that issue:

public void ConfigureAuth(IAppBuilder app)
{
    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider()
        {
            OnApplyRedirect = ctx =>
            {
                if (!IsApiRequest(ctx.Request))
                {
                    ctx.Response.Redirect(ctx.RedirectUri);
                }
            }
        }
    });
    
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
}


private static bool IsApiRequest(IOwinRequest request)
{
    string apiPath = VirtualPathUtility.ToAbsolute("~/api/");
    return request.Uri.LocalPath.StartsWith(apiPath);
}

11 comments:

  1. Awesome.! Really very helpful. Thankx...

    ReplyDelete
  2. That was really helpful thanks.

    ReplyDelete
  3. Thanks, It helped me as well, it took me a while to find this solution.

    ReplyDelete
  4. avast secureline vpn login, avast secureline, avast secureline vpn activation code, avast secureline tap adapter v3, avast secureline vpn virus, avas Avast Vpn Activation Code

    ReplyDelete
  5. The writing tool that helps you produce text documents quickly and easily using mind maps. App available on macOS and Windows PCs and iPad.https://cyberspc.com/writemapper-full-crack-download/

    ReplyDelete
  6. Hi.
    This writing tool is a game-changer, enabling you to effortlessly create text documents by utilizing mind maps. Available on both macOS and Windows platforms, this app streamlines the process, allowing you to produce content rapidly and with ease. Here is sharing some SnapLogic Training information may be its helpful to you.

    SnapLogic Training

    ReplyDelete