0

I'm trying to catch events where a 401 occurs (expired token) so I can send a request to re-authorise a user with a new token. My problem is the response code is not reached when the response is 401:

angular.module('app')
       .factory('authInterceptor',

function ($rootScope, $q, $window) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
        console.log('not 401');
      }
      return config;
    },
    response: function (response) {
      console.log(response.status);
      if (response.status === 401) {
        // handle the case where the user is not authenticated
        console.log('401 !!!!!!!');
      }
      return response || $q.when(response);
    }
  };
});

Other people have solved this by not including the WWW-Authenticate header, I've tried this and the response function still wasn't called. I'm thinking of just using another status code to work around the problem but I'd prefer not to.

1 Answer 1

1

When the response is 401, this is an error (All 4x are errors). You should use the property responseError to check that.

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

Check $http documentation https://docs.angularjs.org/api/ng/service/$http

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.