Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Omniauth-twitter in rails: OAuth::Unauthorized 401

I have been road blocked for 2 days on basic omniauth authentication with twitter. I followed along with Ryan Bates' railscast on simple omniauth, but have been unable to get past the OAuth::Unauthorized 401 exception that is raised when I try to log in. Please help! My code is pasted below:

    twitter info: 
    website: [http://127.0.0.1:3000]
    callbarck url: [http://127.0.0.1:3000/auth/twitter/callback]

//routes.rb

    Sentimentalist::Application.routes.draw do

    resources :dashboard, only: [:index]
    resources :welcome

    root :to => 'welcome#index'

    match '/auth/twitter/callback', to: 'sessions#create'

    match "/signout" => "sessions#destroy", :as=>:signout


   match ':controller(/:action(/:id))(.:format)'
end

//application.html.erb

            <!DOCTYPE html>
    <html>
    <head>
      <title>Sentimentalist</title>
      <%= stylesheet_link_tag    "application", :media => "all" %>
      <%= javascript_include_tag "application" %>
      <%= csrf_meta_tags %>
      <% yield(:head) %>
    </head>
    <body>
        <div id="container">
            <div id="user_nav">
                    <% if current_user %>
                      Welcome <%= current_user.name %>!
                      <%= link_to "Sign Out", signout_path %>
                    <% else %>
                      <%= link_to "Sign in with Twitter", "/auth/twitter" %>
                    <% end %>
            </div>
       </div>

     <%= yield %>

    </body>
    </html>

// config/initializers/omniauth.rb

    Rails.application.config.middleware.use OmniAuth::Builder do
      provider :twitter, '###', '###'
    end

// sessions_controller.rb

    def create
      auth = request.env["omniauth.auth"]
      user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]) ||User.create_with_omniauth(auth)
      session[:user_id] = user.id
      redirect_to root_url, :notice => "Signed in!"
    end

    def destroy
      session[:user_id] = nil
      redirect_to root_url, :notice => "Signed out!"
    end
like image 619
user2040608 Avatar asked Jun 05 '13 02:06

user2040608


1 Answers

There is problem when you set your app callback url to localhost.
Try to set your twitter applcation's callback url using a url shortner.

You could use a url shortner like http://goo.gl/ and replace your callback url with the one that fits you.

http://127.0.0.1:3000/auth/twitter/callback => http://goo.gl/QVYCy
like image 124
oldergod Avatar answered Nov 03 '22 14:11

oldergod