get_access_token always returns 401 Unauthorized


#1

I am trying to use 3-legged authentication to get user’s access token. This is just a prototype, so it is not implemented with session yet to save some returned data of API. Please read through the comment below. In application setting I have also setup callback_url in application settings at dev.twitter.com.

require 'oauth'

oauth = OAuth::Consumer.new(MY_CONSUMER_KEY, MY_CONSUMER_SECRET, { site:  "https://twitter.com" })
request_token = oauth.get_request_token(oauth_callback: 'http://mywebsite.com/caller')
rtoken = request_token.token 
rsecret = request_token.secret 
puts rtoken #=> R_TOKEN_RECVD , I save this string and noted on a paper
puts rsecret #=> R_SECRET_RECVD, I save this string and noted on a paper
redirect_to request_token.authorize_url #=> https://twitter.com/oauth/authorize?oauth_token=R_TOKEN_RECVD


# After user authorizes, user is redirected to http://mywebsite.com/caller?oauth_token=OAUTH_TOKEN_RETURNED&oauth_verifier=OAUTH_TOKEN_VERIFIER
# I note down OAUTH_TOKEN_VERIFIER on a paper. Then I created a new ruby file, xx.rb that has code as follows:

# xx.rb

oauth = OAuth::Consumer.new(MY_CONSUMER_KEY, MY_CONSUMER_SECRET, { site: "https://twitter.com" })
new_request_token = OAuth::RequestToken.new(oauth, R_TOKEN_RECVD, R_SECRET_RECVD) # Remember above, I have that noted down R_TOKEN_RECVD and R_SECRET_RECVD on a paper

response = new_request_token.get_access_token(oauth_verifier: OAUTH_TOKEN_VERIFIER) # This call always fails in OAuth::Unauthorized: 401 Unauthorized

So anyone have any idea why I am getting 401. I have spent several hours finding the reason, but no success. I searched at google as well as dev.twitter.com, but no luck. Any help will be appreciated. Please don’t suggest me to save token and secret to save in session and then use in xx.rb. As I said above, it is just a prototype.