【发布时间】: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