Angular http interceptors not applied for requests initialised from within interceptors?
In our codebase, every request to our api has an url that starts with /api/ and we have an interceptor that updates those requests with the actual address of our api (making it easy to switch between an development and production environment for one thing).
After updating the url, the interceptor also adds an Authorization header if an access token is present. This all works perfectly.
However, sometimes the access token is expired, but we still have an refresh token and before continuing with the actual request, I first want to make an request to our api to obtain a new access token.
So, in the request part of our interceptor, we call a service responsible for refreshing the access token and in a then callback returned by that method, we update the config of the original request:
//This interceptor only applies to our api calls, do nothing for other requests
if(config.url.substring(0, API_PREFIX.length) !== API_PREFIX) {
return config;
}
config.url = config.url.replace(API_PREFIX, API_ENDPOINT);
// if we are authenticated, we add the authorization header already
if(AuthSessionService.isAuthenticated()) {
config.headers['Authorization'] = "Bearer " + AuthSessionService.getAccessToken();
return config;
}
// so we are not authenticated, but we still do have a refresh-token, this means, we should get a new access-token
if(AuthSessionService.hasRefreshToken()) {
var deferred = $q.defer(),
loginService = angular.injector(['MyApp']).get('LoginService');
loginService.refresh().then(function(result) {
config.headers['Authorization'] = "Bearer " + AuthSessionService.getAccessToken();
deferred.resolve(config);
}).catch(function() {
deferred.reject('Failed to refresh access token');
});
return deferred.promise;
}
//no access-token, no refresh-token, make the call without authorization headers
return config;
However, the requests made by the login-service do not seem to have the interceptor applied, so the request goes to /api/login instead of the actual api endpoint.
Is this by Angular's design, that no interceptor is applied when a new http request is being made from within an interceptor's request method?
loginService? I'm guessing it has a dependency to$http, right? So that would be a circular dependency issue. I'm guessing the workaround is the cause of your issue. - Sergiu Paraschiv$http- charlietfl$http) before, but without result luck. So I tried it this way, but no luck either. - schmkr