Google-chrome – User authentication with XMLHttpRequest works in IE, not in Chrome

authenticationgoogle-chrometwitterwebkitxmlhttprequest

The following function works in IE but not in Chrome:

function doStuff() {
  var request = new XMLHttpRequest();
  request.open("POST", "http://twitter.com/statuses/update.json", true, "USERNAME-HERE", "PASSWORD-HERE");
  request.send("status=STATUS UPDATE HERE");
}

Chrome generates the following request. Note the Authorization header is missing:

OPTIONS /statuses/update.json HTTP/1.1
Host: twitter.com
Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/532.5 (KHTML, like Gecko) Chrome/4.0.249.78 Safari/532.5
Access-Control-Request-Method: POST
Origin: file://
Access-Control-Request-Headers: Content-Type
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

I get the following response (http 401):

HTTP/1.1 401 Unauthorized
Date: Wed, 03 Feb 2010 00:39:33 GMT
Server: hi
Status: 401 Unauthorized
WWW-Authenticate: Basic realm="Twitter API"
X-Runtime: 0.00107
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache, max-age=300
Set-Cookie: _twitter_sess=BAh7BzoHaWQiJTUxMTc2Nzk4N2U0YzMzZmU0ZTQyNzI4NjQyYjI3ODE2Igpm%250AbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAG%250AOgpAdXNlZHsA--bb61324c3ba12c3cd1794b3895a906a69c154edd; domain=.twitter.com; path=/
Expires: Wed, 03 Feb 2010 00:44:33 GMT
Vary: Accept-Encoding
Content-Length: 73
Connection: close

{"request":"/statuses/update.json","error":"Could not authenticate you."}

So, how am I supposed to pass a username and password to XHR? Webkit/Safari documentation says the open method should take these parameters, so I'm not sure why it is failing.

Best Answer

The solution was that I needed to add

request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

The way I'm doing this is... special... so this may not be of much use to others going forward. But once I added this webkit started adding Authorization.

Related Topic