Search code examples
apitwitteroauthaccess-token

How to use "user context access token" that I get from Twitter OAuth 1.0a in my request?


I have successfully (?) implement the Twitter three-legged authentication process to obtain user access token. The problem is the access token appears invalid... or I use it wrong. I already able to get the app's access token, which can access limited Twitter API. I use it by adding "Authentication: Bearer 'access token'" on the header. But when I did the same thing with the user context access token and did the same request, I always get error code 89 Invalid or expired token.

The access token I obtained has a structure of [several numerics]-[some alpha numeric chars]. Like 12345678-asd98f798asdf79asdfa9sdfs9df7a9sdf7. This looks similar with the access token example in step 3 of https://developer.twitter.com/en/docs/basics/authentication/oauth-1-0a/obtaining-user-access-tokens.

I also notice that the example request there is like this:

POST statuses/update.json
oauth_consumer_key=cChZNFj6T5R0TigYB9yd1w
oauth_token=7588892-kagSNqWge8gB1WwE3plnFsJHAZVfxWD7Vb57p0b4

Which I presume those two additional parameters are to be added to the body instead of the header. But, how if my request is a GET request? Like request to get home timeline, which absolutely requiring user context access token?

https://developer.twitter.com/en/docs/tweets/timelines/api-reference/get-statuses-home_timeline

From this API ref, the example only give the GET url, and not how to supply the user context access token. Please help. I have the feeling that the solution is very simple (like a fix on the header), but I can't see it.

This is my current request:

curl -X GET \
  'https://api.twitter.com/1.1/users/show.json?screen_name=huffpost' \
  -H 'Authorization: Bearer 12345678-as3d12a3d1a3sd1232ads13asd123as1d23as3d32,Bearer 12345678-as3d12a3d1a3sd1232ads13asd123as1d23as3d32' \

This is the result:

{
    "errors": [
        {
            "code": 89,
            "message": "Invalid or expired token."
        }
    ]
}

Solution

  • The user access token requires signing a request which includes parameters and headers.

    https://developer.twitter.com/en/docs/basics/authentication/oauth-1-0a/authorizing-a-request

    You can use a library like https://github.com/twitter/joauth to generate the signature.

    For Java+OkHttp - you can use this library https://github.com/yschimke/okurl/blob/master/src/main/kotlin/com/baulsupp/okurl/services/twitter/joauth/Signature.kt#L33