Simple Ruby OAuth with Twitter

We’ve been working on creating a website that would access resources within the cloud, and decided on adopting OAuth as an enabler. The difficulty was in finding a concise and simple example on how to do just that. Everywhere people had fully integrated rails models, controllers and libraries, or complicated explanations with gaps in the code provided.

To fix the problem, we’ve come up with a very simple OAuth example using the Twitter Provider. You’ll need the oauth gem for this to work:

#!/usr/bin/env ruby
 
require 'rubygems'
require 'oauth'
 
consumer = OAuth::Consumer.new "twitter_provided_consumer_key",
                     "twitter_provided_secret_key",
                      { :site => 'http://twitter.com/',
                        :request_token_path => '/oauth/request_token',
                        :access_token_path => '/oauth/access_token',
                        :authorize_path => '/oauth/authorize'}
 
request_token = consumer.get_request_token
puts "Place \"#{request_token.authorize_url}\" in your browser"
print "Enter the number they give you: "
pin = STDIN.readline.chomp
 
access_token = request_token.get_access_token(:oauth_verifier => pin)
 
puts access_token.get('/account/verify_credentials.json')

As you can see, the OAuth gem deals with most of the dirty work, as a matter of fact, almost half of the example file is environment, dependencies and user interaction. There is really only three lines that have any real use.

Tags: , , , ,

Comments

  • Thanks a lot for the post!

  • Thank you from your example.
    Unfortunately my ruby seems not so well set up.. it claims “./OAuth.rb:7: uninitialized constant OAuth (NameError)”, just in line 2:
    - require ‘OAuth’

    Any suggestion?
    Thank you
    Adit

  • Ehm sorry! I’m a total noob.. I named my test file ‘oauth.rb’ overriding the require directive. Just had to name my file to something like ‘test.rb’ and worked XD

    Anyway, thank you this excellent article!

  • [...] eventually found a blog post at BeefyApps which cleared things up immensely, and so I’ve now reshuffled their code snippet into a mini command line utility which will [...]

Post a Comment

Your email is not published nor shared.