Basic Authentication With XMLHTTPRequest

x1a0 picture x1a0 · Oct 30, 2009 · Viewed 67.1k times · Source

I am attempting to use XMLHTTPRequest to get an update on twitter.

var XMLReq = new XMLHttpRequest();
XMLReq.open("GET", "http://twitter.com/account/verify_credentials.json", false, "TestAct", "password");
XMLReq.send(null);

However, using my sniffer I cannot see any authorization headers being passed through. Hence, I get a 401 error response from Twitter.

The account and password are correctly entered.

Anyone attempt this? Can anyone give me some pointers? Thank you.

Answer

Vitor Arbex picture Vitor Arbex · Apr 9, 2015

You just need to add a Authorization header, an user name and password in a base64 encoded string as follows.

XMLReq.setRequestHeader("Authorization", "Basic " + btoa("username:password"));