Can't get OAuth2 bearer token

oauth

#1

I’m attempting to get my App-Only bearer token from the Twitter Oauth2 API. Depending on how I do it, I get either error 400 (Bad Request) or 503 (Service Temporarily Unavailable). I’m stumped.

Attempt 1 was via an HTTPS socket (in Xojo, if you must know); when that failed I dropped down to a raw SSL socket, so that I know exactly what I’m sending. I’m sending this (with the credentials ellided here):

POST /oauth2/token HTTP/1.1
Host: api.twitter.com
User-Agent: My Twitter App v1.0.23
Authorization: Basic MUs1NGpvd (...stuff deleted...) MmpxeQ==
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
Content-length: 29
Accept-Encoding: gzip

grant_type=client_credentials

This request is modeled directly after the one in the docs. It produces a 400 (Bad Request) error code.

Then I decided to try curl (again, credentials ellided):

curl -i -d 'grant_type=client_credentials' -H 'Authorization: Basic MUs1NGpv (...blah blah...) mpxeQ==' -H 'Content-Type: application/x-www-form-urlencoded;charset=UTF-8' 'https://api.twitter.com/oauth2/token'

And this produces a 503 status code every time.

My credentials are just the Base64 version of my API key and secret, joined by a colon. The same key and secret work fine when tested with STTwitterDemoOSX. I’m almost (but not quite) desperate enough to use WireShark to see what that app is sending. But there must be something simple I’m doing wrong. Any ideas?


#2

Here’s a script that does this using curl in case that might help to compare what is going on here?


#3

Thank you, that helped! By comparing line by line, I found that I somehow had a line break in my authorization string. Don’t I feel sheepish. Thanks again for getting me unstuck!


#4

I had the same issue and Andy answer helped me too.
In fact, in my case, the error came from the encoded64 call.

In Ruby in the module Base64 you have several possible type of calls.

  • encode64 will return the base64 encoded value but add line feeds every 60 characters
  • strict_encode64 will return the base64 encoded value without line feeds

In fact you must use strict_encode64 otherwise your encoded value is broken and the POST call will return a 400 http error


#5