B
B
Bogopodoben2016-11-11 15:50:13
Angular
Bogopodoben, 2016-11-11 15:50:13

How to resubmit unsuccessful requests?

There is authorization by JWT. After the token expires and a request is sent to the server for some data, the server sends a new token in the header and puts it in localstorage. But the requests are returned with a 401 error.
The crux of the problem is how to collect these requests and resend with a refreshed token?
provider example:

$httpProvider.interceptors.push(['$q', '$location', 'jwtHelper', 'authServices', '$injector',
      function($q, $location, jwtHelper, authServices, $injector) {
        return {
          request: function(config) {
            var token = localStorage.getItem('auth');
            if(token) {
              config.headers = config.headers || {};
              config.headers.Authorization = 'Bearer ' + token;
            }
            return config;
          },
          requestError: function(rejection) {
            return $q.reject(rejection);
          },
          response: function(response) {
            var storedToken = localStorage.getItem('auth'),
            receivedToken = response.headers('Authorization');
            if(receivedToken && storedToken !== receivedToken) {
              localStorage.setItem('auth', receivedToken);
            };
            return response;
          },
          responseError: function(rejection) {
            switch (rejection.status) {
              case 401:
              receivedToken = rejection.headers('Authorization');
              if (receivedToken) {
                localStorage.setItem('auth', receivedToken);
              };
              console.log(receivedToken);
              break;
              case 403:
              break;
            }
            return $q.reject(rejection);
          }
        };
      }]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg Drapeza, 2016-11-16
@SuperOleg39ru

Good afternoon!
Briefly, how I solved this problem:
A separate service is responsible for saving and updating the token, let's call it Session.
In the interceptors phase of the request , you are doing everything right, this adds a token on each request. We pass to the responseError
phase : 1) Determine the required type of error 2) You can limit the number of repeated requests, and redirect to the login page (here is a nuance, you need to reset the counter in the response phase - a successful response) 3) Send a request to renew the token 4) If successful , call the $http service with the parameters of this request Code example:

responseError: function(rejection) {
  ...

  if (tokenError) {
    return Session.refreshToken().then(function() {
        return $http(rejection.config); // Повторяем запрос, когда получили новый токен
    });
  }

  return $q.reject(rejection);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question