Prarthana Hegde Prarthana Hegde - 8 months ago 49
AngularJS Question

AngularJS - set common Basic Auth header that is applied to all http requests

I am using AngularJS with Play REST services on the back end and I'm fairly new to both concepts.
I want to know if there is a way in which I can write the Basic Auth header at just one place so that is is added by default to every http request that is being made by Angular.

Right now I am adding this line at the beginning of every request.

$http.defaults.headers.common['Authorization'] = 'Basic ' + Base64.encode(username + ':' + password);

I want it to be present at just one place instead of multiple places for easier code maintainability.
Thanks in advance!


You can do this by using an $http interceptor in your angular.config

var app = angular.module();
app.config(['$httpProvider', function($httpProvier){


  return {
    request: function(config) {
      config.headers.Authorization = YOUR_AUTHORIZATION_HEADER;
      return config;