3

I need to set a global http header to all my requests because of the authentication method that we are using. We have an Identity Server to authenticate the user using a SSO approach. So far so good, we were using interceptors to set headers globally. But sometimes we need to make a request to a 3rd party API that doesn't use any authentication method. How can I override the authentication header that was configured by the interceptor? Is it a recommended approach for this problem?

Bruno Casarotti
  • 623
  • 8
  • 23

1 Answers1

2

In your interceptor, you can write some logic to decide if you need to add the header or not:

.factory('AuthHeaderInterceptor', function () {

  function request(config) {

    //if 3rd party url, don't add auth header
    if(config.url.indexOf('third_party_url') !== -1) {
      return config;
    }

    config.headers.Authorization = 'auth header';
    return config;
  }

  return {
    request: request
  };
});
yvesmancera
  • 2,915
  • 5
  • 24
  • 33
  • 1
    Thanks, Now it seems to be so obvious! Probably the best way. Just another thing that I thought but I am not sure if it works: if I create a service to my third party (is this a good thing to do by the way?) can I override the harder or actually it would be overridden in the interceptor? – Bruno Casarotti Sep 01 '15 at 23:43
  • 1
    Glad I could help! I'm not sure what you mean by "override the harder". As far as I know, the interceptor would catch any HTTP requests (yeah, not only API calls, even requests for css/html/js files). I don't see why creating a service for a third party is a bad idea, I'd say go for it. – yvesmancera Sep 02 '15 at 00:14
  • 1
    Sorry, I mean override the header. – Bruno Casarotti Sep 02 '15 at 00:17
  • 1
    Considering your service is still going through angular's `$http` service, yeah, the request would pass through the interceptor. – yvesmancera Sep 02 '15 at 00:19