Ennio
Ennio

Reputation: 1157

How can I make $http with authentication?

I have make a POST request to an API and they have basic authentication, how can I tell angular $http POST service to pass my credential while making the post requestion?

Upvotes: 1

Views: 66

Answers (1)

Rohit Rai
Rohit Rai

Reputation: 286

You can add auth interceptor as follows

angular.module('interceptors.authInterceptor',[])

.factory('authInterceptor', ['$q', function ( $q) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      config.headers['Authorization'] = 'Bearer ' + YOUR_AUTH_TOKEN;
      return config;
    },
    response: function (response) {
      return response || $q.when(response);
    },
    responseError: function(rejection) {
    }    

  };
}])

.config(['$httpProvider', function ($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
}]);

Upvotes: 3

Related Questions