Tag: AngularJS
Redirecting to login page with AngularJs and .net WebAPI

Redirecting to login page with AngularJs and .net WebAPI

So here's the scenario, you have a web application which people log into and some of the pages (like a dashboard) contain ajax functionality. Inevitably the users session expires, they return to the window change a filter and nothing happens. In the background, your JavaScript is making http calls to the server which triggers an unauthorised response. The front end has no way to handle this and some errors appear in the JS console.

A few things are actually combining to make life hard for you here. Lets take a look at each in more detail.

WebAPI and the 301 Response

To protect your API's from public access a good solution is to use the Authorize attribute. i.e.

1public ActionResult GetDashboardData(int foo)
3 // Your api logic here

However chances are your solution also has a login page configured in your web.config so that your regular page controller automatically trigger a 301 response to the login page.

1 <authentication mode="Forms">
2 <forms timeout="30" loginUrl="/account/sign-in/" />
3 </authentication>

So now what happens, is instead or responding with a 401 Unauthorised response, what's actually returned is a 301 to the login page.

With an AJAX request from a browser you now hit a second issue. The browser is making an XMLHttpRequest. However if that request returns a 301, rather than returning it your JavaScript code to handle, it "helpfully" follows the redirect and returns that to your JavaScript. Which means rather than receiving a 301 redirect status back, your code is getting a 200 Ok.

So to summarise your API was set up to return a 401 Unauthorised, that got turned into a 301 Redirect, which was then followed and turned into a 200 Ok before it gets back to where it was requested from.

To fix this the easiest method is to create are own version of the AuthorizedAttribute which returns a 403 Forbidden for Ajax requests and the regular logic for anything else.

1using System;
2using System.Web.Mvc;
4namespace FooApp
6 [AttributeUsage(AttributeTargets.Method)]
7 public class CustomAuthorizeAttribute : AuthorizeAttribute
8 {
9 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
10 {
11 if (filterContext.HttpContext.Request.IsAjaxRequest())
12 {
13 filterContext.Result = new HttpStatusCodeResult(403, "Forbidden");
14 }
15 else
16 {
17 base.HandleUnauthorizedRequest(filterContext);
18 }
19 }
20 }

Now for any Ajax requests a 403 is returned, for everything else the 301 to the login page is returned.

Redirect 403 Responses in AngularJs to the login page

As our Ajax request is being informed about the unauthorised response, it's up to our JavaScript code trigger the redirect in the browser to the login page. What would be really helpful would be to define the redirect logic in one place, rather than adding this logic to every api call in our code.

To do this we can use add an interceptor onto the http provider in angular js. The interceptor will inspect the response error coming back from the XmlHttpRequest and if it has a status of 401, use a window.locator to redirect the user to the login page.

1app.factory('httpForbiddenInterceptor', ['$q', 'loginUrl', function ($q, loginUrl) {
2 return {
3 'responseError': function (rejection) {
4 if (rejection.status == 403) {
5 window.location = loginUrl;
6 }
7 return $q.reject(rejection);
8 }
9 };
12app.config(['$httpProvider', function ($httpProvider) {
13 $httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
14 $httpProvider.interceptors.push('httpForbiddenInterceptor');

You'll notice a line updating the headers. This is to make the IsAjaxRequest() method on the api recognise the request as being Ajax.

Finally you'll also notice the loginUrl being passed into the interceptor. As it's not a great idea to have strings like urls littered around your code, this is using a value recipe to store the url. The code to do this is follows:

1app.value('loginUrl', '/account/sign-in?returnurl=/dashboard/');