401 unauthorized error handling in AngularJS 401 unauthorized error handling in AngularJS angularjs angularjs

401 unauthorized error handling in AngularJS


The accepted answer doesn't work for later versions of angular. Using 1.5.x (and maybe even earlier) you need to write the interceptor differently:

// http interceptor to handle redirection to login on 401 response from APIapp.factory('httpResponseInterceptor', ['$q', '$rootScope', '$location', function($q, $rootScope, $location) {    return {        responseError: function(rejection) {            if (rejection.status === 401) {                // Something like below:                $location.path('signin/invalidSession');            }            return $q.reject(rejection);        }    };}]);

Apply with:

app.config(function($httpProvider) {    $httpProvider.interceptors.push('httpResponseInterceptor');});

See here for further information https://docs.angularjs.org/api/ng/service/$http#interceptors


i needed to do very similar recently, here is my interceptor

app.factory("HttpErrorInterceptorModule", ["$q", "$rootScope", "$location",    function($q, $rootScope, $location) {        var success = function(response) {            // pass through            return response;        },            error = function(response) {                if(response.status === 401) {                    // dostuff                }                return $q.reject(response);            };        return function(httpPromise) {            return httpPromise.then(success, error);        };    }]).config(["$httpProvider",    function($httpProvider) {        $httpProvider.responseInterceptors.push("HttpErrorInterceptorModule");    }]);

modified slight for your use case


In case of any API call returns 401 we have to redirect user to login page. Angular’s HTTP interceptor is great for that job. As you can see from app.js above, it’s been pushed to pipe here:

httpProvider.responseInterceptors.push('httpInterceptor');

The interceptor implementation itself,

'use strict';angular.module('dashboardApp').factory('httpInterceptor', function httpInterceptor ($q, $window, $location) {  return function (promise) {      var success = function (response) {          return response;      };      var error = function (response) {          if (response.status === 401) {              $location.url('/login');          }          return $q.reject(response);      };      return promise.then(success, error);  };});