46

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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
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.
@AakilFernandes It's only a configuration. You can inject $http directly.
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.
38
$http.defaults.headers.common['Auth-Token'] = 'token';

It seems headers() normalizes the key names.

3 Comments

Can you elaborate on what you mean by normalizes the key names?
When getting the headers using the headers() method, the key "Auth-Token" gets lowercased and becomes "auth-token". Which is confusing.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.