Detecting API auth failures in JavaScript

Home / Detecting API auth failures in JavaScript

In .NET when I’m dealing with WebAPI controllers, I like to secure them.  Typically, this is done with an [Authorize] attribute on the controller or the controller’s actions.

One problem that arises with .NET, though, is that a user’s auth token/cookie could be expired because they are inactive for a set amount of time.  Imagine that you’ve written a shiny new SPA-type web app and is SOA driven.  When the user resumes accessing your site, all of the API end-points will fail until the user logs back in.


We wind up having to manage this situation for ourselves since API’s typically don’t have logins.  The user won’t be automatically redirected to login, obviously.  In Angular, request interceptors come to mind.  If you’re using jQuery or vanilla JavaScript, the mechanisms will be essentially the same – inspect the response status at the global level.

For the Angular use case, our request interceptor becomes really simple:

(function () {
    var authInterceptor = function ($q, $window) {
        return {
            'response': function (response) {
                return response || $q.when(response);
            },

            'responseError': function (rejection) {
                if (rejection.status == 401) {
                    // Notify user - assume that our current state url requires auth too
                    // We can reload the current location which causes a redirect to login
                    $window.location.reload();
                }
                return $q.reject(rejection);
            }
        };
    };

    authInterceptor.$inject = ['$q', '$window'];
    angular.module('myApp.infrastructure')
        .factory('authInterceptor', authInterceptor);
})()

In this interceptor, all we’re interested in is the responseError callback. If we see a 401 status, we use the $q service to reject the response and simply reload the page. This reloading should cause the user to be redirected to our login page.

In jQuery, we could also intercept an $.ajax() call using handlers in the global settings.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.