尝试从Google OAuth 2.0获取access_token时,为什么会出现404错误?

时间:2012-02-09 18:21:32

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

我目前正在构建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

2 个答案:

答案 0 :(得分:3)

搞定了!

好像我错过了几件事:

  1. 添加了HTTP请求的SSL设置。
  2. 将参数作为正文发送,而不是作为请求的一部分发送。
  3. 正确地将内容类型放入请求中。
  4. 我希望这有助于那里的人!

    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)
    

答案 1 :(得分:1)

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

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

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