Search code examples
angularjsangular-httpangular-http-interceptorsangular-http-auth

Correct way to set and override a request header in Angular


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?


Solution

  • 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
      };
    });