Rails OAuthException ::必须使用活动访问令牌来查询有关当前用户的信息

时间:2013-03-12 11:32:28

标签: ruby-on-rails-3 facebook-oauth fb-graph

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

 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令牌无效的全部内容。

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

1 个答案:

答案 0 :(得分: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