Tuesday, April 26, 2016

Prevent Redirect to Login page for Unauthorized Calls to Web API

If you have implemented token based authorization to your Web API which resides in an ASP.NET MVC application, you would probably come across this situation. Because, you have login page to MVC application which will be shown if you are not logged in. In case of Web API calls, you are obviously not logged in, but credentials or access token is passed in the request header.

Just include the following code fragment in the startup class just before the app.UseWebApi(config); line, to prevent this redirect for unauthorized Web API calls such the access token is not provided or got expired.

            // Important: Enable Suppress redirect to login page if token is invalid
            app.Use((context, next) =>
            {
                HttpContext.Current.Response.SuppressFormsAuthenticationRedirect = true;
                return next.Invoke();
            });

            var config = new HttpConfiguration();
            WebApiConfig.Register(config);
            app.UseWebApi(config);

1 comment:

  1. I found this article easy to understand and very helpful. Can’t wait to see the other posts. Thank you for sharing!


    Melbourne Web Developer

    ReplyDelete