Csati Csati - 1 year ago 245
AngularJS Question

Capture HTTP 401 with Angular.js interceptor

I'd like to implement authentication on a single page web app with Angular.js. The official Angular documentation recommends the using of interceptors:

$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {

// ...

'responseError': function(rejection) {
// do something on error
if (canRecover(rejection)) {
return responseOrNewPromise
return $q.reject(rejection);

The problem is when the server sends 401 error, the browser immediately stops with "Unauthorized" message, or with login pop-up window (when authentication HTTP header is sent by the server), but Angular can't capture with it's interceptor the HTTP error to handle, as recommended. Am I misunderstanding something? I tried more examples found on web (this, this and this for example), but none of them worked.

Answer Source

in app config block:

var interceptor = ['$rootScope', '$q', "Base64", function(scope, $q, Base64) {
  function success(response) {
    return response;

  function error(response) {
    var status = response.status;
    if (status == 401) {
      window.location = "/account/login?redirectUrl=" + Base64.encode(document.URL);
    // otherwise
    return $q.reject(response);
  return function(promise) {
    return promise.then(success, error);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download