0

我在我的 rails 应用程序中使用fb_graph来获取和设置访问令牌(如果它通过 facebook 进行身份验证)。我有一个邀请控制器,用户必须在其中进行身份验证才能邀请朋友。我的代码如下所示:

 def facebook
   if params[:code]
     set_oauth_token(params[:code])
   elsif params[:error]
     redirect_to landing_path, :alert => "Access Denied"
     return
   end

   if current_user.oauth_token.nil?
     redirect_to client.authorization_uri(
     :scope => "user_about_me, email, publish_stream, user_location, user_interests, user_birthday, user_likes, user_hometown, offline_access"
      )
   end

 private

 def set_oauth_token(token)
   client.authorization_code = params[:code]
   access_token = client.access_token! :client_auth_body
   user = FbGraph::User.me(access_token).fetch
   current_user.oauth_token = access_token
   current_user.save(:validate => false)
 end

  def client
    FbGraph::Auth.new(ENV["FACEBOOK_KEY"], ENV["FACEBOOK_SECRET"], :redirect_uri =>  invites_facebook_url).client
  end

但我得到了错误:

 FbGraph::InvalidRequest at /invites/facebook
 OAuthException :: An active access token must be used to query information about the current user.

错误在以下行:

user = FbGraph::User.me(access_token).fetch

我试图寻找解决方案并修改了代码,但仍然无法解决问题。oauth 令牌无效。

请帮我找到解决方案。非常感谢!!

4

1 回答 1

1

最后我得到了错误,那就是在回调之后你必须再次点击 facebook 才能获得 oauth 令牌。我已经修改了我的代码并且它有效。

用户模型

def self.auth(redirect_url)
    FbGraph::Auth.new(ENV["FACEBOOK_KEY"], ENV["FACEBOOK_SECRET"], :redirect_uri =>  redirect_url)
end

用户控制器

def facebook
  if params[:code]
    set_oauth_token(params[:code])
  elsif params[:error]
    redirect_to landing_path, :alert => "Access Denied"
    return
  end

  if current_user.oauth_token.nil?
    client = User.auth(invites_facebook_url).client
    redirect_to client.authorization_uri(
    :scope => "user_about_me, email, publish_stream, user_location, user_interests, user_birthday, user_likes, user_hometown, offline_access"
    )
 end
end

private

  def set_oauth_token(token)
    client = User.auth(invites_facebook_url).client
    client.authorization_code = params[:code]
    access_token = client.access_token! :client_auth_body
    user = FbGraph::User.me(access_token).fetch
    current_user.oauth_token = access_token
    current_user.save(:validate => false)
  end
于 2013-03-18T11:10:53.720 回答