Rails EOF使用HTTP.get_response检索Facebook访问令牌时出错

Dav*_* W. 5 ruby facebook ruby-on-rails oauth

我试图在我的网站上实现Login with Facebook功能,并试图从Facebook获取访问令牌.这是我的代码:

if params[:error_reason] == "user_denied" then
  flash[:error] = "To login with Facebook, you must click 'Allow' to let the site access your information"
  redirect_to :login
elsif params[:code] then
  token_uri = URI.parse("https://graph.facebook.com/oauth/access_token?client_id=****************&redirect_uri=http://localhost:3000/auth/fblogin&client_secret=***************&code="+URI.escape(params[:code]))
  response = Net::HTTP.get_response(token_uri)
  session[:response] = response
  data = ActiveSupport::JSON.decode(response)
  access_token = data[:access_token]
  flash[:error] = access_token
  redirect_to :register
end
Run Code Online (Sandbox Code Playgroud)

这是一个fblogin控制器函数,它是获取授权代码(params[:code])的初始重定向的目标.

但是当我遇到这个问题时,我收到以下错误:

EOFError in AuthController#fblogin

Net::HTTP.get_response(token_uri)行了.我到处搜索过,找不到任何表明这意味着什么的东西.它可能是Facebook在访问令牌中使用的模糊字符吗?我完全迷路了!

Mic*_*ley 10

您收到的是EOFError因为您尝试https使用仅适用的代码连接到URL http.有关基础知识,请参阅此Net :: HTTP备忘单中标题为"SSL/HTTPS请求"的部分.

不过,我会建议使用第三方库来管理这个给你,如OAuth2用户的使用Facebook的API的OAuth2,在那里你会写这样的代码:

def client
  OAuth2::Client.new('app_id', 'app_secret', :site => 'https://graph.facebook.com')
end

# in your callback code:
access_token = client.web_server.get_access_token(params[:code], :redirect_uri => 'http://localhost:3000/auth/fblogin')
user = JSON.parse(access_token.get('/me'))
Run Code Online (Sandbox Code Playgroud)

如果您真的想自己提出请求,可以查看像Faraday这样的库来为您执行HTTPS请求.