2

I'm trying to write a $http interceptor which will attach a header in order to authorize the application with a token.

I have an auth service which requests and stores the token for future use.

In the application config, I'm configuring $httpProvider and pushing a new interceptor onto the array.

The interceptor depends on my Auth service, in order to get hold of the token to send each time. In turn, the Auth service depends on $http in order to send the initial request to authenticate and retrieve the auth token.

I end up with a circular dependency graph that looks something like:

 $httpProvider ^ \ / v $http <- Auth Service 

Auth depends on $http, and through $httpProvider, $http depends on Auth.

Is there an elegant way to get around this? I thought about using an intermediate service, but ultimately, that would just be extending the dependency graph. Something needs to be fundamentally changed.

Is it possible to do something like resolve and reconfigure $http after the auth token has been retrieved?

2
  • You could just set the $http default headers, see the Setting HTTP Headers section Here Commented Nov 11, 2014 at 20:34
  • I want to control which API endpoints see the auth token. Doing it with interceptors allows me to control them within the request handler. I guess I could set default headers and then remove them in a HTTP interceptor which doesn't depend on Auth, but that seems kinda messy. Commented Nov 11, 2014 at 23:28

1 Answer 1

2

You want to use $injector to manually get a hold of your authentication service.

angular.module('app.services.authentication') .factory('AuthenticationHeaderInterceptor', ['$injector', AuthenticationHeaderInterceptor]); function AuthenticationHeaderInterceptor ($injector) { var service = { request: addAuthenticationHeader }; return service; function addAuthenticationHeader (config) { var token = null; // Need to manually retrieve dependencies with $injector.invoke // because Authentication depends on $http, which doesn't exist during the // configuration phase (when we are setting up interceptors). // Using $injector.invoke ensures that we are provided with the // dependencies after they have been created. $injector.invoke(['Authentication', function (Authentication) { token = Authentication.getAuthenticationHeaders(); }]); if (token) { angular.extend(config.headers, token); } return config; } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.