User authentication using XMLHttpRequest works in IE and not in Chrome?

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 creates the following query. Please note that 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 should I pass the XHR username and password? The Webkit / Safari documentation says that the public method should accept these parameters, so I'm not sure why it fails.

+4
source share
3 answers

The solution was that I needed to add

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

The way I do this is ... special ... so it may not be very useful to others. But as soon as I added that this web kit started adding authorization.

+3
source

In appearance, you are trying to execute the XML-HTTTPRequest X-Domain, so Chrome sends a request before the OPTIONS flight. Since the Twitter server is not responding to an OPTIONS request indicating that access to the X-Domain is ok, you get a failure here.

Your code will only work in IE in the local computer zone or if you disable domain verification (very dangerous)

+3
source

You tried:

 request.setRequestHeader('Authorization', 'yourvalue'); 
+2
source

Source: https://habr.com/ru/post/1300127/


All Articles