27

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.

x1a0
  • 456
  • 3
  • 7
  • 8

3 Answers3

78

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

XMLReq.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
starball
  • 20,030
  • 7
  • 43
  • 238
Vitor Arbex
  • 916
  • 6
  • 7
10

In cross-origin requests, you have to explicitly set the withCredentials flag if you want user credentials to be sent.

See http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute (where user credentials includes HTTP authentication)

Thomas Broyer
  • 64,353
  • 7
  • 91
  • 164
  • 2
    New links are https://xhr.spec.whatwg.org/#the-withcredentials-attribute and https://xhr.spec.whatwg.org/#user-credentials – sberder Nov 07 '16 at 10:55
3

Due to the Origin policy, you cannot make a XMLHttpRequest from your domain to another domain. E.g. you cannot use http://twitter.com/... URLs unless your script was loaded from twitter.com. If your script is loaded from http://localhost/, the AJAX request also need to go to localhost.

mhaller
  • 14,122
  • 1
  • 42
  • 61
  • 5
    You _can_ make XHR requests to another server, but that other server must set CORS headers for the request to not be rejected by the browser you're using (unless your using a dodgy browser that ignores the lack of CORS headers). – Griknok Apr 19 '18 at 07:12