Search code examples
angularjsdependency-injectionaccess-tokeninterceptorcircular-dependency

Angularjs Interceptor Circular Dependency when using Refresh Tokens


Long story short, I have a structure in my angularjs app which is basically the following: 1. There is an 'authService' that is in charge of requesting access tokens, and refresh tokens. 2. There is an 'authInterceptorService' that adds the token to the header of the request, however, the tricky part is here: this service depends on the authService, for generating a new access token using a refresh token in case the access token is expired and the request is 401en, which means there will ultimately be a circular dependency, when I use the $httpProvider service to register the interceptor:

authService <- authInterceptorService <- $http <- authService

My questions is how is it possible to get around this issue when your interceptor needs to be able to issue a new access token using the refresh token and REsend the request?


Solution

  • One way to get around this would be use to Angular's event system. Since you are dealing with services you would probably need to broadcast the event ($emit) and listen for it ($on) on $rootScope.

    For example, you can setup a listener for a 'tokenExpired' event that calls your token refresh service, which when successful fires a 'tokenRefreshed' event. When a request is 401'd you emit the tokenExpired event and register a one-time listener for the tokenRefreshed event in order to re-send the request after the refresh.

    Maybe not the cleanest solution, but I've used setups like this when dealing with gnarly dependency chains and it works pretty well.