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",
                      { :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.