Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic Authentication With XMLHTTPRequest

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.

like image 837
x1a0 Avatar asked Oct 30 '09 20:10

x1a0


People also ask

How do I send a correct authorization header for basic authentication?

Basic Auth: The client sends HTTP requests with the Authorization header that contains the word Basic, followed by a space and a base64-encoded(non-encrypted) string username: password. For example, to authorize as username / Pa$$w0rd the client would send.

Does XMLHttpRequest send cookies?

XMLHttpRequest can make cross-origin requests, using the same CORS policy as fetch. Just like fetch , it doesn't send cookies and HTTP-authorization to another origin by default.

What is XMLHttpRequest withCredentials?

The XMLHttpRequest. withCredentials property is a boolean value that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-origin requests.


2 Answers

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")); 
like image 165
Vitor Arbex Avatar answered Sep 21 '22 12:09

Vitor Arbex


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)

like image 41
Thomas Broyer Avatar answered Sep 21 '22 12:09

Thomas Broyer