【问题标题】:Why do I get a 404 Error when attempting to get an access_token from google OAuth 2.0?为什么我在尝试从 google OAuth 2.0 获取 access_token 时收到 404 错误?
【发布时间】:2012-02-11 01:29:16
【问题描述】:

我目前正在构建 OAuth 授权,仅用于获取电子邮件和个人资料信息。

我可以使用以下方法轻松获取代码:

def authorize
  base = "https://accounts.google.com/o/oauth2/auth?"
  params = {
    :scope => "https://www.googleapis.com/auth/userinfo.profile",
    :redirect_uri => "http://localhost:3000/oauth/callback/",
    :client_id => "id",
    :response_type => 'code'
  }
  redirect_to base + params.to_query
end

但是,当我尝试从 Google 获取访问令牌时,我收到 404 错误:

def callback
  code = params[:code]
  client_id = 'id'
  client_secret = 'secret'
  redirect_uri = "http://localhost:3000/oauth/callback/"
  http = Net::HTTP.new('accounts.google.com', 80)
  path = "https://accounts.google.com/o/oauth2/token?"
  headers = {'Content-Type'=>"application/x-www-form-urlencoded" }
  parameters = "code=#{code}&grant_type=authorization_code&client_secret=#{client_secret}&client_id=#{client_id}&redirect_uri=#{redirect_uri}"
  resp, data = http.post(path,parameters,headers)
end

response code: 404  data: Google Home | Sign in

The page you requested is invalid.

我不完全确定问题可能是什么。我尝试与复制+粘贴注册的回调 URL 匹配。我多次检查了我的参数,但找不到可能导致错误的原因。

我正在关注Google documentation 并使用以下信息向 Google 注册:

Client ID for web applications 
Client ID: id
Client secret: secret
Redirect URIs: http://localhost:3000/oauth/callback/ 
JavaScript origins: none

【问题讨论】:

  • 他们是否进行了重定向? Net::HTTP 不会像 Open-URI 那样自动处理它们,但 Open-URI 不支持 POST。你可能会看看 Typhoeus,它处理得很好。
  • 根据谷歌的文档,它应该返回一个带有访问令牌或错误的 json blob。此调用不应有重定向。

标签: ruby-on-rails ruby oauth-2.0


【解决方案1】:

搞定了!

似乎我错过了几件事:

  1. 为 HTTP 请求添加了 SSL 设置。
  2. 将参数作为正文而不是请求的一部分发送。
  3. 将内容类型正确放入请求中。

我希望这对那里的人有所帮助!

param = {
  :code => params[:code],
  :client_id => client_id,
  :client_secret => client_secret,
  :redirect_uri => "http://localhost:3000/oauth/callback/",
  :grant_type => 'authorization_code'
}

uri = URI.parse("https://accounts.google.com/o/oauth2/token")
http = Net::HTTP.new(uri.host, uri.port)
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
http.use_ssl = true
request = Net::HTTP::Post.new(uri.request_uri)
request["Content-Type"] = "application/x-www-form-urlencoded"
request.body = param.to_query
response = http.request(request)

【讨论】:

  • 仅供参考,我不得不将端口硬编码为 443,因为 uri.port 返回 80(Ruby 1.9.2 Rails 3.0.9)
【解决方案2】:

如果您试图让 Google 重定向到:

:redirect_uri => "http://localhost:3000/oauth/callback/",

我怀疑他们找不到localhost。给他们你的真实 IP 号码。

【讨论】:

  • 我相信这不是问题。获取令牌的初始调用正常工作。他们返回到我的 localhost 机器,甚至在他们的表单上签署了应用程序。我会尝试部署到heroku并在那里进行实验。
猜你喜欢
  • 2021-09-23
  • 2022-01-26
  • 2015-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
  • 2013-08-09
  • 2016-03-28
相关资源
最近更新 更多