Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh Token in Interceptor before request is fired

Pulling my hair out on this one. I would like to refresh an access token if the user's access token is just about to expire.

authService.isUserLoggedIn() returns a promise and checks if the the user is logged in or not. If not the user's access token is being refreshed.

However the problem is that authService.isUserLoggedIn() is async call and before it returns the value, the interceptor will finish its job and the Authorization header will not be populated with the new token...

I was looking for a way to wait for the promise to resolve before the script continues. Unfortunately I'm not able to complete what is required.

Code:

.factory('SEHttpInterceptor', function($injector, ngWebApiSettings) {
    return {
        // optional method
        'request': function(config) {

          // add Authorization header if available
          if (config.url.indexOf(ngWebApiSettings.apiServiceBaseUri) >-1){
            var authService = $injector.get('authService2');
              authService.isUserLoggedIn().then(function(response){
                var authData = $injector.get('$localStorage').getObject("authorizationData");
                config.headers.Authorization = 'Bearer ' + authData.token;
              });
          }   
          return config;
        }
      };
});
like image 314
Chris Ciszak Avatar asked Jan 17 '15 20:01

Chris Ciszak


1 Answers

From AngularJS $http documentation:

The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.

I'm assuming that you can simply:

'request': function(config) {

    if (config.url.indexOf(ngWebApiSettings.apiServiceBaseUri) === -1){
        return config;
    }

    var authService = $injector.get('authService2');
    return authService.isUserLoggedIn().then(function(response){
        var authData = $injector.get('$localStorage').getObject("authorizationData");
        config.headers.Authorization = 'Bearer ' + authData.token;
        return config;
    });

}
like image 147
Oleg Avatar answered Nov 15 '22 00:11

Oleg