DMfll DMfll - 5 months ago 83
Ruby Question

401 unauthorized from Twitter API with oauth gem in Ruby

This is my first experience working with Twitter API's.
I am using the following tools:

  • ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-linux]

  • gem 'oauth'

    • oauth (0.5.1)

    • oauth2 (1.1.0)

    • omniauth-oauth2 (1.4.0)

I obtained a key and secret from Twitter.

I copied and pasted from the example on Twitter for Ruby.

code taken directly from the example at

require 'oauth'
consumer_key, \
consumer_secret = [
].map { |key| ENV[key] }
raise "Some key undefined." unless [consumer_key, consumer_secret].all?

# Exchange your oauth_token and oauth_token_secret for an AccessToken instance.
def prepare_access_token(oauth_token, oauth_token_secret)
consumer ="APIKey", "APISecret", { :site => "", :scheme => :header })

# now create the access token object from passed values
token_hash = { :oauth_token => oauth_token, :oauth_token_secret => oauth_token_secret }
access_token = OAuth::AccessToken.from_hash(consumer, token_hash )

return access_token

# Exchange our oauth_token and oauth_token secret for the AccessToken instance.
access_token = prepare_access_token(consumer_key, consumer_secret)
p access_token

# use the access token as an agent to get the home timeline
response = access_token.request(:get, "")
p response


|| #<OAuth::AccessToken:0x000000021ed938
@token="redacted", @secret="redacted",
@secret="APISecret", @options={:signature_method=>"HMAC-SHA1",
:proxy=>nil, :scheme=>:header,
:http_method=>:post, :oauth_version=>"1.0",
@params={:oauth_token=>"redacted", :oauth_token_secret=>"redacted"}>
|| #<Net::HTTPUnauthorized 401 Authorization Required readbody=true>

What I tried:

Suggestions of where to go from here appreciated.

UPDATE OAuth Tool on Twitter Developer returns the expected result with a curl execution:

curl --get '' --header 'Authorization: OAuth oauth_consumer_key="redacted", oauth_nonce="redacted", oauth_signature="redacted", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1463742270", oauth_token="redacted", oauth_version="1.0"' --verbose

Expected data is returned.

[{"created_at":"Fri May 20 11:05:21 +0000

"733614584754515968","text":"Three Skills Every New Programmer Should
Learn https://t. co/1p9AxO5JPg via


On this line, you should replace "APIKey" and "APISecret" with what you pulled from the CONSUMER_* environment variables.

consumer ="APIKey", "APISecret", { :site => "", :scheme => :header })

The example code from Twitter works fine for me. The wrong consumer keys will give you 401 for sure.