我有一个使用
https://github.com/intridea/oauth2的rails项目.在我的rails应用程序中,我有以下代码:
ApplicationController.rb
def facebook_client
OAuth2::Client.new(FacebookOauthCredentials::APP_ID, FacebookOauthCredentials::APP_SECRET, :site => 'https://graph.facebook.com')
end
FacebookController.rb
def facebook_session_create(poster, featured_item)
redirect_to facebook_client.web_server.authorize_url(:scope => 'publish_stream', :redirect_uri => "http://localhost:3000/facebook/facebook_callback")
end
def facebook_callback
if(params[:code])
begin
access_token = facebook_client.web_server.get_access_token(params[:code], :redirect_uri => "http://localhost:3000/facebook/facebook_callback")
access_token.post('/me/feed', "testing #{rand(1000)}")
rescue OAuth2::HTTPError => e
render :text => e.response.body
end
end
end
每次运行此代码时,我都会得到以下响应:
{"error":{"type":"OAuthException","message":"Error validating verification code."}}
但是,我使用OAuth2 gem的自述文件中提供的sinatra应用程序,它工作正常.
def client
OAuth2::Client.new(FacebookOauthCredentials::APP_ID, FacebookOauthCredentials::APP_SECRET, :site => 'https://graph.facebook.com')
end
get '/auth/facebook' do
redirect client.web_server.authorize_url(
:redirect_uri => redirect_uri,
:scope => 'publish_stream'
)
end
get '/auth/facebook/callback' do
access_token = client.web_server.get_access_token(params[:code], :redirect_uri => redirect_uri)
begin
user = JSON.parse(access_token.post('/me/feed', :message => "testing # {rand(10000)}"))
rescue Exception => e
return e.response.body
end
user.inspect
end
def redirect_uri
uri = URI.parse(request.url)
uri.path = '/auth/facebook/callback'
uri.query = nil
uri.to_s
end
我尝试使用irb重现这些步骤,但我有一个http 400错误.我不确定它是否与rails应用程序的原因相同,或者是因为我正在进行控制台和Web浏览器操作的混合.任何建议将不胜感激.
最佳答案 我在这个页面
Facebook graph API – OAuth Token找到了我的问题的答案
I ran into the exact same problem but
it turned out the issue is not the
encoding of the redirect_uri
parameter, or that I had a trailing
slash or question mark it’s simply
that I passed in two different
redirect urls (had not read the
specification at that time).The redirect_uri is only used as a
redirect once (the first time) to
redirect back to the relying party
with the “code” token. The 2nd time,
the redirect_uri is passed back to the
auth server but this time it’s not
used as you’d expect (to redirect)
rather it’s used by the authentication
server to verify the code. The server
responds with the access_token.You’ll notice facebook documentation
(which is terrible) says fetch
“Exchange it for an access token by
fetching ….
“In summary, I didn’t have to encode or
do anything special to the Uri, just
pass in the same redirect_uri twice,
and fetch the 2nd page to get the
access_token inside.
我没有正确复制我的原始代码和重定向uri我传递的代码不同于我传递的uri来获取访问令牌. Facebook的API文档非常糟糕:(