Supporting http auth url's using AngularJS

For an application I'm working on I need Angular to successfully check for (any) content on a HTTP-Auth protected url such as


Googling on how to support this gives some overly complex solutions. Most will either config a default header on the $http service or set a default Authorization header before doing an $http.get, both of which are wrong (at least in my case when the url may change)

Additionally they implement their own base64 encoding.

And then you still don't support the auth-encoded url itself. The solution I came up with is trivially simple:


 var creds = "";
var credmatch = remote.match("https?://(.+?)@");
if(credmatch) {
    creds = btoa(credmatch[1]);
$http({method: "GET",
url: remote,
headers: {
Authorization: "Basic " + creds
}).then(function(result) {
console.log("PING success");
self._status = "connected";

 As you can see, it simply sets the Authorization header as part of the request itself. And it's using the widely available 'btoa' to do the encoding (well, for me the availability is sufficient). Parsing the url is done using a simple regexp.


Last updated April 13, 2015, 4:30 p.m. | angularjs $http auth
comments powered by Disqus