0

I am invoking an API from angular JS front end and I am getting the 401 Unauthorized error. Here are the options I have tried.

Option 1:

$http({
    method: "GET",
    xhrFields: {
        withCredentials: true
    },
    headers: {
        Authorization: 'Basic ' + btoa('user:password')
    },
    url: 'http://localhost:11000/api/ping'
}).then(function(r) {
    return Session.userId = r.headers('user');
})

Can you please help me in passing the credentials to backend API?

Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299
  • Have you tried debugging your code by checking the Network tab in your browser's developer tools to see what headers are sent? – mostruash Jan 04 '16 at 21:16
  • Are you using ASP .Net forms authentication? – Avi Jan 04 '16 at 21:21
  • Response Headers Access-Control-Allow-Credentials:true Access-Control-Allow-Headers:accept, authorization Access-Control-Allow-Methods:GET Access-Control-Allow-Origin:http://localhost:8000 Allow:GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH Content-Length:0 Date:Mon, 04 Jan 2016 21:19:46 GMT Server:Apache-Coyote/1.1 Strict-Transport-Security:max-age=31536000 ; includeSubDomains Vary:Origin WWW-Authenticate:Basic realm="Spring" – how it works Jan 04 '16 at 21:22
  • Request Headers view source Accept:*/* Accept-Encoding:gzip, deflate, sdch Accept-Language:en-US,en;q=0.8 Access-Control-Request-Headers:accept, authorization Access-Control-Request-Method:GET Connection:keep-alive Host:localhost:11000 Origin:http://localhost:8000 Referer:http://localhost:8000/app/ user:samuel – how it works Jan 04 '16 at 21:22
  • No Avi, I am not using .Net forms. – how it works Jan 04 '16 at 21:22
  • @Avi, ASP.NET Forms Authentication doesn't use Basic Authentication. – Darin Dimitrov Jan 04 '16 at 21:22
  • Additional Info, I have tried accessing the API by SoapUI and its working fine. – how it works Jan 04 '16 at 21:24

1 Answers1

0

if you make an $http request you have to use a promise because of the asynchronus

function httpReq (){
    return $http({ // this will return a promise
      method: 'GET',
      url: '/someUrl'
    }).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        console.log('success');
        return response;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        console.log('error');
        return response;
    });
}

and how to use the promise returned by the function

httpReq().then( function (res) {
    console.log(res);
});
AlainIb
  • 4,544
  • 4
  • 38
  • 64