Problem with Twitter basic authentication using AJAX
- by jelford
I'm developing a javascript App that needs, as part of its functionality, for users to be able to update their Twitter status. The App is designed to work on mobiles, and as such I don't really want to be sending users all the way over to the Twitter site to sign in; they should just be able to pass their credentials to the app, and I'll handle all the signin.
So I'm trying to use the Basic Auth with the restful API. My code looks like:
function postTweet(input){
$.ajax( {
type: "POST",
url: "http://twitter.com/statuses/update.json",
data: {status: input},
dataType: "json",
error: function() { alert("Some error occured"); },
success: function() { alert("Success!"); },
beforeSend: function(request) { request.setRequestHeader("Authorization", "Basic BASE64OFMYCREDENTIALS");}
} ) ;
}
So, as far as I'm aware, this should perform the authentication from the XMLHttpRequest header, and then post the status.
However, whenever I call this code, I get a "401 Unauthorized" error from Twitter.
Below are the request & response headers from firebug:
Request:
OPTIONS /statuses/update.json HTTP/1.1
Host: twitter.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: null
Access-Control-Request-Method: POST
Access-Control-Request-Headers: authorization
Response:
HTTP/1.1 401 Unauthorized
Date: Sat, 13 Mar 2010 11:08:58 GMT
Server: hi
Status: 401 Unauthorized
WWW-Authenticate: Basic realm="Twitter API"
X-Runtime: 0.00204
Content-Type: application/json; charset=utf-8
Cache-Control: no-cache, max-age=300
Set-Cookie: guest_id=1268478538488; path=/
_twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCPlyNlcnAToHaWQiJWUyN2YzYjc3OTk2NGQ3%250ANzJkYTA4MjYzOWJmYTQyYmUyIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--d687808459872da0aa6a89cab35fd347300b4d07; domain=.twitter.com; path=/
Expires: Sat, 13 Mar 2010 11:13:58 GMT
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 88
Connection: close
Any help with this would be much appreciated,
Thanks,
jelford
ps. I should mention I'm using JQuery, incase it's not clear.