Search code examples
ruby-on-railsapitwitteromniauthomniauth-twitter

RoR Twitter API oAuth : "Could not authenticate you."


I try to connect my app to the Twitter API. I am not sure but i think my problem come from the oauth_signature. So i read this documentation : https://dev.twitter.com/oauth/overview/creating-signatures

I think i did everything like they say but it's doesn't work and i don't have any clues why.

Here is my code :

  def build_url_api(parameters, token, account, secret_token)
   consumer_key = 'xxx'
   secret_consumer_key = 'xxx'

   oauth_consumer_key = consumer_key
   oauth_signature_method = "HMAC-SHA1"
   oauth_timestamp = Time.zone.now.to_i.to_s
   oauth_nonce = Digest::SHA256.hexdigest(oauth_timestamp)[0..16]
   oauth_version = "1.0"
   oauth_token = token
   url = 'https://api.twitter.com/1.1/statuses/user_timeline.json'

   parameters = 'oauth_consumer_key=' +
   oauth_consumer_key +
   '&oauth_nonce=' +
   oauth_nonce +
   '&oauth_signature_method=' +
   oauth_signature_method +
   '&oauth_timestamp=' +
   oauth_timestamp +
   '&oauth_token=' +
   oauth_token +
   '&oauth_version=' +
   oauth_version

   base_string = 'GET&' + CGI.escape(url) + '&' + CGI.escape(parameters)
   secret_key = secret_consumer_key + '&' +secret_token
   oauth_signature = CGI.escape(Base64.encode64("#{OpenSSL::HMAC.digest('sha1',secret_key, base_string)}").chomp)
   url = url + '?' + parameters + '&oauth_signature=' + oauth_signature
 end

An exemple of an URL i created thanks to my code :

https://api.twitter.com/1.1/statuses/user_timeline.json?oauth_consumer_key=xxx&oauth_nonce=4f8f5638b6aa6e132&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1487703144&oauth_token=15028214-zk3HGlrA7zYOv2DGasrL9MJMXNqFsk1g6q4TEOS9V&oauth_version=1.0&oauth_signature=iNVkhyCCFBXP2He6LfCFL0ukwxQ%3D

Thanks in advance for anyone who can give me an idea !

PS : of course i replace here the consumer_key and secret_key whith 'xxx'


Solution

  • Shame on me i found the solution :

    I just had an old consumer_key.

    My code sample here works well.