Integrate twitter oAuth in your rails application

By , June 11, 2009 12:11 am

Now Twitter is using oAuth service to intergrate with your web application. There are the few steps that you need to follow to use it.

First of all you need to get your consumer key and consumer secret. You will get these details by register your application on twitter.

After getting consumer key and consumer secret, you need to install oauth gem.

$ sudo gem install oauth
Password:
Successfully installed oauth-0.2.7
1 gem installed
Installing ri documentation for oauth-0.2.7...
Installing RDoc documentation for oauth-0.2.7...

Now create a new application.

rails twitteroauth
cd twitteroauth

Create User scaffold in your application.

ruby script/generate scaffold user screen_name:string token:string secret:string
rake db:create
rake db:migrate

Add below code in UserController

Note: Because latest oauth gem, changes made in create and callback method on 29/04/2010
def self.consumer
# The readkey and readsecret below are the values you get during registration
OAuth::Consumer.new("YOUR CONSUMER KEY", "YOUR CONSUMER SECRET",{ :site=>"http://twitter.com" })
end
def create
@request_token = UsersController.consumer.get_request_token(:oauth_callback => "callback-url-of-your-twitter-app")
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

This action gets a request token from Twitter and then redirects the user to Twitter to authorize access. This action does not call User.new, that is delayed until the user returns from the Twitter authorization.
In the registration above we registered the callback URL as /users/callback, so let's add that action:

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_tokenn(:oauth_verifier => params[:oauth_verifier])
@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
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
end

Add below code in /users/show.html.erb

<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>
<%= link_to 'Back', users_path%>

/users/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 %>

route.rb

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

Now you have call users/new url and you will be able to login via Twitter account.

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Webnews
  • Digg
  • del.icio.us
  • Reddit
  • Bloglines
  • LinkedIn
  • YahooMyWeb
  • Facebook
  • Google Bookmarks
  • Mixx
  • MySpace
  • Technorati
  • TwitThis

31 Responses to “Integrate twitter oAuth in your rails application”

  1. Hey, great post, very well written. You should write more about this.

  2. Brijesh Shah says:

    Thanks. I will definitely written on this when I will get more things on this.

  3. NoJ says:

    Actually this is just a copy of the original posting at

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

  4. Brijesh Shah says:

    yes you are right…But this one is more proper way than that…

  5. Ritesh Pareek says:

    Hi Brijesh,

    I am trying for twitter oauth login from last couple of days, but i am getting following response every time

    _______________________________________________________
    You’ve successfully granted access to Eyes fo Ubuntu!

    Simply return to Eyes fo Ubuntu and enter the following PIN to complete the process.
    5767819
    ——————————————-

    I follow your way as well, but :( . Is there any mistake in twitter application “Eyes of ubuntu” or what? Please help me on this

    Thanks

    Ritesh PAreek

  6. Brijesh Shah says:

    Can you tell me where you tested this application? on localhost or live server?

    because on localhost, it just return the grant access number. You have to tested on liver server with registered domain (which you need to setup in twitter/ouath_clinets app config).

  7. Ritesh Pareek says:

    aahh.. i got it… it was not my code problem, it was with oauth gem 0.3.5. i uninstall it and install 0.3.4. thanks to following link

    http://stackoverflow.com/questions/1262694/why-do-users-have-to-enter-a-7-digit-twitter-pin-to-grant-my-application-access

  8. Ritesh Pareek says:

    Hi,

    I was on my stagging server and now it is working fine.

    Thnaks a lot for your reply

    Regards

    Ritesh PAreek

  9. Brijesh Shah says:

    thanks for this information.

  10. Raghu Raj says:

    I am getting this message “You’ve successfully granted access to treetMe!

    Simply return to treetMe and enter the following PIN to complete the process.” while using the oauth API.

    Raghu Raj

  11. Ankit Parekh says:

    Hi Raghu Raj,

    the solution is
    simply make changes as mentioned below in your users_controller

    def create
    @request_token = UsersController.consumer.get_request_token( :o auth_callback => \"callback-url-of-your-twitter-app\" )
    …..
    …..
    end

    def callback
    @access_token = @request_token.get_access_token( :o auth_verifier => params[:oauth_verifier])
    @response = UsersController.consumer.request(:get, \’/account/verify_credentials.json\’,
    @access_token, { :scheme => :query_string })
    …..
    …..
    end

    Thanks
    Ankit Parekh

  12. Ritesh Pareek says:

    Hi Raghu,

    I also faced same problem while working on tweetMe, in my case it was related to api version. whenI was using twitter api 6.0.1 there was no problem but with 6.1.5 same problem is there.

    As Ankit replied, if you not provied callback url it will ask for PIN access(usally for desktop application) for web it is callback url.

    Thanks

  13. mel says:

    hi i’m trying your code for a couple of days, on localhost the callback part never works always give timed out connection, and in a live server give this: The page you were looking for doesn’t exist. can you help me please!

    thanks

    Mel

  14. Brijesh Shah says:

    Hi Mel,

    On localhost, twitter ouath never works because of real domain is required as callback path.You need to define callback path which is get request and process further as it is defined on callback function.

    Note: Callback path must be same n application setting on twitter and in your and :o auth_callback parameter in create method.

    Let me know if you have any problems.

    Thanks
    Brijesh Shah

  15. mel says:

    Hi thanks for your reply, now the code works fine, i’m just getting a problem with post methods, for example update an status, can you help me with that? please? here is my code:

    usersController.consumer.request(:post, ‘/statuses/update.json’, @access_token, ‘status’ => ‘Hello Twitter’)

    I try this but never update the status.. helpe me please :)

    Thanks

    Mel

  16. Brijesh Shah says:

    Hi Mel,

    Use following syntax to post data
    userController.consumer.request(:post,’/statuses/update.json’,@access_token,{},{:status =>”STATUS” })

    let me know if you have still problem?

    Thanks
    Brijesh Shah

  17. mel says:

    Hi thanks for your reply is working now.. :D thank you!!!

  18. Navi says:

    how do I tweet ?
    Below code is not working for me. It says 404 not found
    userController.consumer.request(:post,’/statuses/update.json’,@access_token,{},{:status =>”STATUS” })
    Please help me for the same.

  19. Brijesh Shah says:

    Hi Navi,

    For each twitter request, you need to get access token(a new one). So assign new access token by following action and passed it in your twitter request.
    @access_token = OAuth::AccessToken.new(UsersController.consumer, @user.token, @user.secret)

    Let me know if you still face any problem.

    Thanks
    Brijesh Shah

  20. Radhika says:

    I have given

    @request_token = UsersController.consumer.get_request_token(:oauth_callback => “http://122.183.186.14:5000/callback”)

    in the create method. The callback method is called but throwing an error as

    401 Unauthorized
    OAuth::Unauthorized in UsersController#callback

  21. TT says:

    I have a problem with this
    ——————————————————–
    session[:request_token] = @request_token.token
    session[:request_token_secret] = @request_token.secret

    after callback

    @request_token = OAuth::RequestToken.new(UsersController.consumer,
    session[:request_token],
    session[:request_token_secret])
    ——————————————————

    but after callback my session is empty.
    the only way I can do is save it to database.
    Do you have any idea about this issue?
    Thanks for your help

    • Brijesh shah says:

      Hi

      did you check token and secret values are stored in session variables before called authorize url?
      and also let me know in which rails version are you using?

      Thanks
      Brijesh Shah

  22. NanaPriya says:

    Hi,

    I am using rails 3 and oauth 0.4.4(latest). i have done the above steps. but i got the following error message while booting and did not connect to the server.

    Uncaught exception: undefined local variable or method `map’ for #

    Because of this line “map.connect ‘/callback’, :controller => ‘users’, :action => ‘callback’” in routes.rb

    Please help me. how to solve it?

    Thanks,
    Priya.

    • Brijesh shah says:

      Hi Priya,

      use match ‘callback’ => ‘users#callback’,:as => ‘callback’ instead of “map.connect ‘/callback’, :controller => ‘users’, :action => ‘callback’”

      define routes are different in rails 3.

      Thnaks
      Brijesh Shah

      • NanaPriya says:

        Hi Brijesh,

        Thanks for your immediate reply. yes now my server conncted. but i got “404 unathorized”.

        Actually what will i give for this “callback-url-of-your-twitter-app” in create method of usercontroller.I gave “/users/callback”. i think something problem on this line.

        @request_token = UsersController.consumer.get_request_token(:oauth_callback => “callback-url-of-your-twitter-app”)

        Thanks,
        Priya.

        • NanaPriya says:

          what i want is, i will get my post on my application. i am getting based on my twitter id and password. so why will i need consumer secret and consumer key?

          Please clarify me

          Thanks,
          Priya

  23. NanaPriya says:

    Hi Brijesh,

    Now i got consumer token and secret keys. I have 3 urls are request token, access token and authorize url. I gave these 3 for callback url. but still i get 401 unAuthorized.

    Can you help me.

    Thanks,
    Priya.

    • NanaPriya says:

      Now i am on localhost. is there any problem with this?. still i receive 401 unauthorized error. what i do? the callback function didn’t call.

      • Brijesh shah says:

        Hi

        Twitter integration is not work with localhost..It will take either ip address or domain name.

        So for twitter integration testing , you need real domain..

        Call back url must be same both side ( in code and application setting)

      • Brijesh shah says:

        Hi

        You can also do one thing to run this app on localhost, when you got 401 error code while you return on callback url.

        Just change domain name with your localhost with portnumber..

        Eg: domainname.com/callback to localhost:3000/callback…

        Thanks
        Brijesh Shah

Leave a Reply

*

Panorama Theme by Themocracy