我实施了OmniAuth + Twitter策略。它适用于大多数用户的大部分时间。但是一些用户已经遇到了一致的失败,我无法重现或追踪它。登录到Twitter后,用户将被重定向到
/auth/failure?message=invalid_credentials
我无法在看到网络流量时在一台用户计算机上运行HTTP调试器,并看到以下内容:
302 GET myserver.com/auth/twitter
CONNECT api.twitter.com:443
401 GET myserver.com/auth/twitter/callback?oauth_token=....&oauth_verifier=....
302 GET myserver.com/auth/twitter/callback?oauth_token=....&oauth_verifier=....
401 GET myserver.com/auth/failure?message=invalid_credentials&strategy=twitter
302 GET myserver.com/auth/failure?message=invalid_credentials&strategy=twitter
一旦用户开始发生这种情况,它就会一遍又一遍地发生,甚至清除cookie并重新启动浏览器也无法解决问题。不确定 - 但它可能只发生在前一天登录并保持浏览器打开的用户。
我用非常轻量级的方法实现了twitter登录,你会看到:
user.rb:
class User
attr_accessor :name, :screen_name, :twitter_secret, :twitter_token
def initialize(auth)
@screen_name = auth['info']['nickname']
@twitter_secret = auth["credentials"]["secret"]
@twitter_token = auth["credentials"]["token"]
@name = auth["info"]["name"]
end
end
session_controller.rb:
class SessionsController < ApplicationController
def reset_and_auth
reset_session
redirect_to '/auth/twitter?force_login=true'
end
def create
user = User.new(request.env["omniauth.auth"])
session[:current_user] = user
redirect_to root_path, :notice => "Signed in!"
end
def destroy
session.delete(:current_user)
redirect_to root_path, :notice => "Signed out!"
end
def failure
flash[:auth_failure] = params[:message]
redirect_to root_path
end
end
application_controller.rb的相关部分:
helper_method :current_user
和
def current_user
session[:current_user]
end
初始化/ omniauth.rb:
twitter_config = YAML.load_file(File.join(Rails.root,'config','twitter.yml'))[Rails.env]
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, twitter_config['consumer_key'], twitter_config['consumer_secret']
end
其他感兴趣的笔记(经过大量谷歌搜索)
宝石版本:
oauth (0.4.6)
omniauth (1.1.0)
hashie (~> 1.2)
rack
omniauth-oauth (1.0.1)
oauth
omniauth (~> 1.0)
omniauth-twitter (0.0.12)
multi_json (~> 1.3)
omniauth-oauth (~> 1.0)
rails (3.2.6)