【问题标题】:Rails EOF Error when using HTTP.get_response to retrieve Facebook access token使用 HTTP.get_response 检索 Facebook 访问令牌时出现 Rails EOF 错误
【发布时间】:2011-07-02 05:09:43
【问题描述】:

我尝试在我的网站上实现使用 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

这是在 fblogin 控制器函数内,它是初始重定向的目标,以获取授权码(params[:code])。

但是当我运行这个时,我得到以下错误:

EOFError in AuthController#fblogin

Net::HTTP.get_response(token_uri) 线上。我已经到处搜索了,找不到任何东西来表明这意味着什么。会不会是 Facebook 在其访问令牌中使用的晦涩字符?我完全迷路了!

【问题讨论】:

标签: ruby-on-rails ruby facebook oauth


【解决方案1】:

您收到EOFError 是因为您尝试使用仅适用于http 的代码连接到https URL。有关基础知识,请参阅this Net::HTTP Cheat Sheet 标题为“SSL/HTTPS 请求”的部分。

但是,我建议您使用第三方库来为您管理,例如 OAuth2 用于利用 Facebook 的 OAuth2 API,您可以在其中编写如下代码:

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'))

如果您真的想自己发出请求,可以查看 Faraday 之类的库来为您执行 HTTPS 请求。

【讨论】:

  • 谢谢,完美的答案!我试图自己编写请求以更好地理解身份验证流程(这只是一个学习项目)。但我会仔细看看 OAuth2!
猜你喜欢
  • 2023-03-05
  • 1970-01-01
  • 2011-12-09
  • 1970-01-01
  • 2012-09-30
  • 2020-09-28
  • 2016-08-30
  • 1970-01-01
相关资源
最近更新 更多