Basic Authentication With XMLHTTPRequest

◇◆丶佛笑我妖孽 提交于 2019-11-26 14:13:26

问题


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.


回答1:


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"));



回答2:


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)




回答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.



来源:https://stackoverflow.com/questions/1652178/basic-authentication-with-xmlhttprequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!