Step by Step Twitter OAuth Integration with Rails

Posted by Dhaval Parikh on Jun 10, 2009 in Uncategorized |

There are many articles posted under this topic but none of them have all information or a Step by Step guide of how to integrate OAuth for use with Twitter Apps and Rails.

So thought of posting one here. Here are few steps which you should follow. The code below is same as provided by the twitter wiki but i have made couple of changes and organized it to make it simple to understand

Step 1 : = You need to get your consumer key and consumer secret # from the twitter OAuth site under this link twitteroauth.

Step 2 := Install OAuth Gem with “gem install oauth” command on ur terminal

Step 3 := Generate a Scaffold using the following command and then migrate the table called “users” to ur database

ruby script/generate scaffold user screen_name:string token:string secret:string

rake db:migrate

Step 4 := Add the following code to your User Controller. Replace the key and secret code with yours :D

def self.consumer

# The readkey and readsecret below are the values you get during registration

OAuth::Consumer.new(“OmwO7wsjtYHjquu6bd6C4w”, “j1kZ6yzsqChkeQtToErUx2LnPQMsSPkXMkiy4F82sPA”,{ :site=>”http://twitter.com” })

end

def create

@request_token = UsersController.consumer.get_request_token

session[:request_token] = @request_token.token

session[:request_token_secret] = @request_token.secret

# Send to twitter.com to authorize

redirect_to @request_token.authorize_url

return

end

Now this is an important part where you need to set the call back url Which u will define while you register your app at twitter OAuth site. Again add this to the UserController

def callback
@request_token = OAuth::RequestToken.new(UsersController.consumer,
session[:request_token],
session[:request_token_secret])
# Exchange the request token for an access token.
@access_token = @request_token.get_access_token
@response = UsersController.consumer.request(:get, ‘/account/verify_credentials.json’,
@access_token, { :scheme => :query_string })
case @response
when Net::HTTPSuccess
user_info = JSON.parse(@response.body)
unless user_info['screen_name']
flash[:notice] = “Authentication failed”
redirect_to :action => :index
return
end

# We have an authorized user, save the information to the database.
@user = User.new({ :screen_name => user_info['screen_name'],:token => @access_token.token,:secret => @access_token.secret })
@user.save!
# Redirect to the show page
redirect_to(@user)
else
RAILS_DEFAULT_LOGGER.error “Failed to get user info via OAuth”
# The user might have rejected this application. Or there was some other error during the request.
flash[:notice] = “Authentication failed”
redirect_to :action => :index
return
end
end
end

As you can see from the comments this callback action exchanges the request token for an access token. Since the user is going to need to type in the username and password at Twitter I avoid prompting for it and instead we fetch that using a call to verify_credentials. This saves duplicate entry and makes it easier on the user. This also prevents users with multiple accounts from giving you one username and then using another when they login to twitter. The access token and secret are what is needed to act on behalf of a user, so those are saved to the database. The show action then uses this information to display some data like so:

def show
@user = User.find(params[:id])
# Get this users favorites via OAuth
@access_token = OAuth::AccessToken.new(UsersController.consumer, @user.token, @user.secret)
RAILS_DEFAULT_LOGGER.error “Making OAuth request for #{@user.inspect} with #{@access_token.inspect}”
@response = UsersController.consumer.request(:get, ‘/favorites.json’, @access_token,
{ :scheme => :query_string })
case @response
when Net::HTTPSuccess
@favorites = JSON.parse(@response.body)
respond_to do |format|
format.html # show.html.erb
end
else
RAILS_DEFAULT_LOGGER.error “Failed to get favorites via OAuth for #{@user}”
# The user might have rejected this application. Or there was some other error during the request.
flash[:notice] = “Authentication failed”
redirect_to :action => :index
return
end

Finally the views

<p>
<b>Screen name:</b>
<%=h @user.screen_name %>
</p>
<ul>
<% @favorites.each do |fav| %>
<li><b><%= fav['user']['screen_name']  %></b>: <%=h fav['text']  %></li>
<% end %>
</ul>

and

the new.html.erb

<h1>New user</h1>

<% form_for(@user) do |f| %>
<%= f.error_messages %>
<p>
We’ll be sending you to Twitter in a moment to login and grant us access.
Once you allow us in we’ll give you the super-cool feature
you’bve heard about.
</p>
<p>
<%= f.submit “Grant Access” %>
</p>
<% end %>
<%= link_to ‘Back’, users_path %>

Also Add validates_presence_of to the User model for screen_name, token and secret.

And in the routes.rb set the following route

map.connect ‘/callback’, :controller => ‘users’, :action => ‘callback’

Thats it you are ready for the twitter Login. Start the server and open localhost:3000/users
and you will see the magic.

These are all the steps. Post me a comment if you still face any isssues.

Please note : – This method might not function correctly now since the method of authentication has changed. Thanks

Be Sociable, Share!

Tags: , , ,

5 Comments

anonymous
Jun 13, 2009 at 2:24 am

http://apiwiki.twitter.com/OAuth+Example+-+Ruby

Cheers! :D


 
dhaval parikh
Jun 13, 2009 at 2:50 am

Yes its from the wiki but in a more organized manner which is easy to understand


 
anonymous
Jun 17, 2009 at 7:13 am

Nice one Dhaval . Thanks its useful blog


 
Lee Munroe
May 14, 2010 at 12:25 pm

Fantastic, this is exactly what I needed. A clear step by step guide.

There are just two things I’m lost on though – where do we define the callback url (apart from in the application settings can’t you pass the url on submitting authorization?)

Also, what does the file ‘/account/verify_credentials.json’ do?

Thanks Dhaval


 

Copyright © 2014 Dhaval Parikh All rights reserved. Theme by Laptop Geek.