5

In my controller I am trying to call my API but I am unable to pass Autherization token.

I have created a config var and passing my token in it but getting following response:

900902Missing CredentialsRequired OAuth credentials not provided. Make sure your API invocation call has a header: "Authorization: Bearer ACCESS_TOKEN"

** JS Code **

 app.controller("AuthenticationController", function($scope, API_URL, vcRecaptchaService, $http) {

       var config = {
         headers: {
           'Authorization': 'Bearer 00000-e5673-346756f-8676-f7567561a'
         }
       };
       $scope.verifyRecaptcha = function() {

         if (vcRecaptchaService.getResponse() === "") {
           alert("User did not resolve the recaptcha")
         } else {
           var post_data = {
             'g-recaptcha-response': vcRecaptchaService.getResponse()
           }
           $http.post('https:1.1.1.1/abc/vdc/verify', config, post_data).success(function(response) {

               if (response.success === true) {
                 alert("Successfully resolved the recaptcha.");
               } else {
                 alert("User verification failed");
               }
             })
             .error(function(error) {
               alert("Error Occured while resolving recaptcha.");
               console.log(error);
             })
         }
       }
Jayant Patil
  • 1,537
  • 2
  • 11
  • 18
Mishi
  • 628
  • 4
  • 16
  • 40
  • Have you tried `$http.defaults.headers.common['Authorization'] = 'Bearer ACCESS_TOKEN ';` refer this https://stackoverflow.com/questions/32425107/angularjs-set-a-authorization-header – Jayant Patil Jul 11 '17 at 07:41
  • This will help you https://stackoverflow.com/questions/30249440/http-post-send-authorization-header – Jayant Patil Jul 11 '17 at 07:46

2 Answers2

2

i think you've switched the position of the payload and the header

should be http.post(url, data, config) instead of http.post(url, config, data)

link to doc

I'd recommend to put all the logic inside an http interceptor, so the auth header will be appended to each request.

Karim
  • 8,454
  • 3
  • 25
  • 33
1

To pass authorization in header, include $httpProvider in your angular module.

And the following function as factory :

function authInterceptor($localStorage) {

        return {
            request: function (config) {
                config.headers = config.headers || {};
                if ($localStorage.token) {
                    config.headers.Authorization = 'Bearer' + 
                    $localStorage.token;
                }
                return config;
            },
        };

    }

And call this factory in your module. So it will add Authorization header in all your $http requests automatically. And you don't need to add authorization header in each request.