[SOLVED] Chrome extension can't gain bearer token (code: 99)

chrome

#1

My source code is quite a simple. I used XMLHttpRequest.

var request = new XMLHttpRequest();
request.open("POST", "https://api.twitter.com/oauth2/token", true, CONSUMER_KEY, CONSUMER_SECRET);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
request.send("grant_type=client_credentials");

I found some says the authorization should be added by setRequestHeader, but it doesn’t make difference.

var request = new XMLHttpRequest();
request.open("POST", "https://api.twitter.com/oauth2/token", true);
request.setRequestHeader("Authorization", "Basic " + btoa(CONSUMER_KEY + ":" + CONSUMER_SECRET));
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
request.send("grant_type=client_credentials");

The result is the below:

{"errors":[{"code":99,"message":"Unable to verify your credentials","label":"authenticity_token_error"}]}

Any idea?


#2

We have some example Chrome extensions on our Github repo that may be helpful.


#3

[SOLVED]
I dumped all headers of the request with Fiddler, and tried with them using cURL. Finally, I found Cookie header causes the issue.

It’s difficult to remove the header with XMLHTTPRequest, so I used Fetch API instead. Fetch API doesn’t attach the header implicitly. However, note that its specification has not stabilized yet.