Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't set an HTTP Basic Auth header in AngularJS

I wrote the following controller for testing out HTTP Basic Auth using Angular JS.

function TestCtrl($scope, $http, Base64){
    $http.defaults.headers.common.Authorization = 'Basic ' + Base64.encode('admin:secret');
    $http.jsonp( 'http://localhost:5000/test'+'/?callback=JSON_CALLBACK', {query:{isArray:true }}).
    then(function (response) {
         $scope.test = response.data;
     });
}

I can see the header being set when i console.log($http.defaults.headers) . But when i check the request headers using Chrome Developer Toolbar or Firebug in Firefox, i don't see the Authorization header.

The server receiving the request doesn't get the Authorization header.

What i am doing wrong here ?

like image 399
Manu Avatar asked Jun 04 '13 17:06

Manu


People also ask

Can we use basic HTTP auth in AngularJS?

AngularJS Authentication ServiceThe Authentication Service is the interface between the angularjs app and the server side api, so http requests are managed here. It also contains a Base64 service for encoding the username and password to be used in the HTTP Authorization header for all requests after logging in.

What is the correct format of Authorization header in basic authentication?

Basic authentication is a very simple authentication scheme that is built into the HTTP protocol. The client sends HTTP requests with the Authorization header that contains the Basic word followed by a space and a base64-encoded username:password string.


1 Answers

I believe the answer is "Yes, for regular AJAX requests you should be able to set the proper auth headers".

However, you're not making a standard XHR call when you use JSONP (based on the example), which changes the answer to "No".

If you're stuck using JSONP, I don't think you can send any auth headers. JSONP simply doesn't work the same as Angular's $http.get for example.

See http://schock.net/articles/2013/02/05/how-jsonp-really-works-examples/ for the details, but the short version is JSONP puts down a <script> tag that fetches some data. The data returned calls the function you provide (JSON_CALLBACK in your example) around the data that the server provides. Because of that, you can't change the headers -- the request is an HTTP GET request exactly as if you'd pasted the URL for the script tag into your browser's location bar.

like image 188
JJ Geewax Avatar answered Sep 19 '22 02:09

JJ Geewax