47

Is there a way to set the $httpProvider headers outside of angular.module('myApp', []).config()?

I'm getting an Auth-Token from the server after I login the user, and I need to add it as a HTTP Header to all following requests.

lucassp
  • 4,133
  • 3
  • 27
  • 36

3 Answers3

67

You can use default headers for angular 1.0.x:

$http.defaults.headers.common['Authentication'] = 'authentication';

or request interceptor for angular 1.1.x+:

myapp.factory('httpRequestInterceptor', function () {
  return {
    request: function (config) {

      // use this to destroying other existing headers
      config.headers = {'Authentication':'authentication'}

      // use this to prevent destroying other existing headers
      // config.headers['Authorization'] = 'authentication';

      return config;
    }
  };
});

myapp.config(function ($httpProvider) {
  $httpProvider.interceptors.push('httpRequestInterceptor');
});

Since factories/services are singletons, this works as long as you do not need to dynamically change your 'authentication' value after the service has been instantiated.

Tim
  • 1,199
  • 1
  • 7
  • 10
  • I like this as a service. Thanks! – grant Jul 17 '14 at 03:22
  • 2
    A bit confused. How do I integrate this into my app? Do I need to list as a dependency and then use `$httpProvider` instead of `$http`? – A F Sep 29 '14 at 21:30
  • Inject $httpProvider into your config method that hangs off of your app module. Providers are a way of configuring services before they get injected by Angular into your controllers etc. – Greg Oct 02 '14 at 14:14
  • @AakilFernandes It's only a configuration. You can inject $http directly. – Leonardo Zanivan Oct 29 '14 at 15:15
  • This is very strange. When i use $http.defaults.headers.common i get an error 405 (Method Not Allowed). I am unsure if the issue here is webapp2 or not. – ADL Mar 28 '17 at 04:21
39
$http.defaults.headers.common['Auth-Token'] = 'token';

It seems headers() normalizes the key names.

lucassp
  • 4,133
  • 3
  • 27
  • 36
  • 3
    Can you elaborate on what you mean by normalizes the key names? – Ben Apr 16 '13 at 15:40
  • 4
    When getting the headers using the headers() method, the key "Auth-Token" gets lowercased and becomes "auth-token". Which is confusing. – lucassp Apr 17 '13 at 08:06
  • @lucassp may be this - http://stackoverflow.com/questions/5258977/are-http-headers-case-sensitive – Midhun KM Jan 10 '16 at 17:50
1

Adding to above responses of @Guria and @Panga

config.headers['X-Access-Token'] = $window.sessionStorage.token;

One can use x-access-token in header as JWT(jsonwebtoken). I store JWT in the session storage when a user authenticate first time.

Pranjal Singi
  • 156
  • 2
  • 8