2013-03-07 115 views
5

當我點擊[http://127.0.0.1:3000/auth/twitter]時,我得到了OAuth :: Unauthorized 401在rails中未經授權的錯誤。我使用Railscast視頻#241跟蹤我的Rails應用程序的Twitter身份驗證。我搜索了很多,但找不到答案。OAuth :: Unauthorized 401未經授權爲omniauth-twitter導軌

Info regarding app on twitter: 
Callback URL: [http://127.0.0.1:3000/auth/twitter/callback] 
Website: [http://127.0.0.1:3000] 


### omniauth.rb 
Rails.application.config.middleware.use OmniAuth::Builder do 
    # provider :developer unless Rails.env.production? 
    provider :twitter, ENV['75UOAIDmKrRXvXKBhNvKA'], ENV['GrIaBI0tQy2TtjOtaFL9VxT6s9qq1sV7h9yRaZW4A'] 
end 

### routes.rb 
Chilli::Application.routes.draw do 
    resources :posts 
    root :to => 'posts#index' 
    #match '/auth/:twitter/callback' => 'sessions#create', :as => :auth_callback 
    match 'auth/twitter/callback', to: 'sessions#create' 
end 

### application.html.erb 
<div id="user_nav"> 
<%= link_to "Sign in with Twitter", "/auth/twitter"%> 
</div> 

### sessions_controller.rb 
class SessionsController < ApplicationController 
    def create 
    user = User.from_omniauth(env['omniauth.auth']) 
    session[:user_id] = user.id 
    redirect_to root_url, notice: "Signed in." 
    end 
end 

### user.rb 
class User < ActiveRecord::Base 
    attr_accessible :name, :provider, :uid 
    def self.from_omniauth(auth) 
    where(auth.slice("provider", "uid")).first || create_from_omniauth(auth) 
    end 

    def self.create_from_omniauth(auth) 
    create! do |user| 
     user.provider = auth["provider"] 
     user.uid = auth["uid"] 
     user.name = auth["info"]["nickname"] 
    end 
    end 
end 
+0

你在twitter.com檢查應用程序的設置?確保你有任何URL作爲回調。 – 2013-03-07 12:26:22

回答

12

omniauth.rb什麼是
ENV['75UOAIDmKrRXvXKBhNvKA'], ENV['GrIaBI0tQy2TtjOtaFL9VxT6s9qq1sV7h9yRaZW4A']

如果75UOAIDmKrRXvXKBhNvKAGrIaBI0tQy2TtjOtaFL9VxT6s9qq1sV7h9yRaZW4A是你APP_IDAPP_SECRET那麼它應該寫成:

provider :twitter, '75UOAIDmKrRXvXKBhNvKA', 'GrIaBI0tQy2TtjOtaFL9VxT6s9qq1sV7h9yRaZW4A' 
+0

@varunvlalan,我厭倦了你的建議,但得到同樣的錯誤。不知道該怎麼辦? – 2013-03-07 09:00:08

+1

我在_routes.rb_ 'match'auth/twitter/callback'中注意到的另一件事情是:'sessions#create'' 用「/」前綴路徑。 'match'/ auth/twitter/callback',to:'sessions#create'' – varunvlalan 2013-03-07 11:01:37

+0

@VSiingh問題是什麼? – OnkelK 2013-07-01 15:27:03

1

我有同樣的問題,有什麼固定我的問題是:

更改:

ENV['75UOAIDmKrRXvXKBhNvKA'],ENV['GrIaBI0tQy2TtjOtaFL9VxT6s9qq1sV7h9yRaZW4A'] 

發給:

'75UOAIDmKrRXvXKBhNvKA', 'GrIaBI0tQy2TtjOtaFL9VxT6s9qq1sV7h9yRaZW4A' 

,並把前一個 '/' '權威性' 在這裏:

match '/auth/:provider/callback', to: 'sessions#create', via: 'get' 
match '/auth/failure', to: redirect('/'), via: 'get' 
相關問題