Twitter OAuth Authentication Using Ruby

October 13, 2009 · 1 min read

Here are the steps involved in using Twitter for OAuth authentication. I wanted this post a few days ago and couldn't find it anywhere, so I wrote it myself.

First, install the required gems:

sudo gem install json oauth

Next, set up your application at http://twitter.com/apps. Make sure you choose Browser as the application type and check the box to use Twitter for login.

A gotcha: if you make a mistake on the new application form, it will silently reset the application type to Client and uncheck the login box. Double-check these settings before saving.

Now for the actual code. Despite the hugely complicated examples floating around elsewhere, you only need two actions: one to initiate the authentication request (the login action) and one to handle the callback when Twitter sends the user back. If you have used OpenID before, this flow should feel familiar.

Your login action looks something like this:

# consumer_key and consumer_secret are from Twitter.
# You'll get them on your application details page.
oauth = OAuth::Consumer.new(consumer_key, consumer_secret,
                             { :site => "http://twitter.com" })

# Ask for a token to make a request
url = "http://whatever.com/login/complete"
request_token = oauth.get_request_token(:oauth_callback => url)

# Take a note of the token and the secret. You'll need these later
session[:token] = request_token.token
session[:secret] = request_token.secret

# Send the user to Twitter to be authenticated
redirect_to request_token.authorize_url

Your callback action looks something like this:

# Your callback URL will receive a request containing an
# oauth_verifier. Use this along with the request token from
# earlier to construct an access request.
request_token = OAuth::RequestToken.new(oauth, session[:token],
                                        session[:secret])
access_token = request_token.get_access_token(
                 :oauth_verifier => params[:oauth_verifier])

# consumer_key and consumer_secret are from Twitter.
# You'll get them on your application details page.
oauth = OAuth::Consumer.new(consumer_key, consumer_secret,
                             { :site => "http://twitter.com" })

# Get account details from Twitter
response = oauth.request(:get, '/account/verify_credentials.json',
                         access_token, { :scheme => :query_string })

# Then do stuff with the details
user_info = JSON.parse(response.body)
# Like find the person that logged in...
Person.find_by_twitter_id(user_info["id"])

If you keep getting 401 Unauthorized errors after implementing this, check that your application is set to Browser mode in the Twitter configuration. That tripped me up for longer than I would like to admit.

These posts are LLM-aided. Backbone, research, original writing, and structure by Craig. Editing by Craig + LLM. Proof-reading by Craig.