arisalexis
arisalexis

Reputation: 2210

How to validate a Twitter access token from the server

The client is able to authenticate using hello.js to facebook and send the access token back to the server which then does a get graph.facebook.com/me?access_token=xx and if it is correct returns the user's profile info.

I want to do the same for Twitter but even after reading the documentation I don't understand which endpoint I should hit.Is it possible to do it with a REST call?

Upvotes: 4

Views: 2290

Answers (2)

Dorian
Dorian

Reputation: 9185

You can make a search query with the access token, e.g.:

curl -X GET 'https://api.twitter.com/2/tweets/search/recent?query=rubyonrails' \
                -H "Authorization: Bearer ZnpQZFV5Y3B2RUxKRHlTcDU3WWNuZWpJQTY3MWlCYWI5OTJlczdwOF9Tanl3OjE3MTI1MTMzMzg1OTI6MToxOmF0OjE"

Here is what you would get when the token is valid and when the token is invalid:

~/s/d/code> curl -X GET 'https://api.twitter.com/2/tweets/search/recent?query=rubyonrails' \
                -H "Authorization: Bearer ZnpQZFV5Y3B2RUxKRHlTcDU3WWNuZWpJQTY3MWlCYWI5OTJlczdwOF9Tanl3OjE3MTI1MTMzMzg1OTI6MToxOmF0OjE"

{"data":[{"edit_...                                                                                                  

~/s/d/code> curl -X GET 'https://api.twitter.com/2/tweets/search/recent?query=rubyonrails' \
                -H "Authorization: Bearer ZnpQZFV5Y3B2RUxKRHlTcDU3WWNuZWpJQTY3MWlCYWI5OTJlczdwOF9Tanl3OjE3MTI1MTMzMzg1OTI6MToxOmF0OjE"

{
  "title": "Unauthorized",
  "type": "about:blank",
  "status": 401,
  "detail": "Unauthorized"
}⏎                                                                                                                                                                                 ~/s/d/code> 

(I refreshed the token so it's invalid now)

Upvotes: 0

arisalexis
arisalexis

Reputation: 2210

You need to hit this endpoint

https://dev.twitter.com/rest/reference/get/account/verify_credentials

like that (using the request module):

const oauth={
    consumer_key:config.get('twitter.consumerKey'),
    consumer_secret:config.get('twitter.consumerSecret'),
    token:oauthToken,
    token_secret:oauthTokenSecret
  }

  requestAsync({
    url:'https://api.twitter.com/1.1/account/verify_credentials.json',
    method:'GET',
    oauth,
  })

Upvotes: 5

Related Questions