Rails + OmniAuth Facebook:如何获取Access Token?

时间:2013-08-07 14:54:34

标签: ruby-on-rails ruby facebook omniauth access-token

我正在尝试从Facebook获取朋友列表。通过Facebook登录不是问题,但问题是要取人的朋友 - 因为access token

puts request.env["omniauth.auth"].inspect
puts '==='
@user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
@fb_user = FbGraph::User.fetch(@user.uid).friends
puts @fb_user.inspect

问题出在第4行 - 在这种情况下我收到错误

OAuthException :: An access token is required to request this resource.

当我把它放在那里时:

@fb_user = FbGraph::User.fetch(request.env["omniauth.auth"].credentials.token).friends

我会得到

OAuthException :: (#803) Some of the aliases you requested do not exist: PRINTED OUT TOKEN

获取access token的正确方法是什么?

编辑:当前流程

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    @user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)
    @fb_user = FbGraph::User.fetch(request.env["omniauth.auth"].credentials.token).friends
    if !@user
      flash[:error] = 'This email address is already used in the system.'
      redirect_to :back
    elsif @user.persisted?
      flash[:notice] = I18n.t "devise.omniauth_callbacks.success", :kind => "Facebook"
      sign_in_and_redirect @user, :event => :authentication
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end

用户模型中:

  def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
    data = access_token.extra.raw_info
    if user = User.where(:provider => 'facebook', :uid => data.id).first
      user
    elsif user = User.where('email = ? AND provider IS NULL', data.email).first
      return false
    else
      ...saving data...
    end
    return user if user
  end

1 个答案:

答案 0 :(得分:4)

您可以通过Facebook Graph API Explorer获取用于测试目的的访问令牌。确保选择要访问的正确字段,然后单击“获取访问令牌”。更永久的解决方案是在Facebook上注册您的应用程序,这样您就可以在没有令牌死亡的情况下不断提出请求。

您应该查看Facebook OAuth dialogue

我假设您尝试使用OAuth2策略而不是Javascript SDK。确保你已经设置了一个回调网址:

client.redirect_uri = "http://your.client.com/facebook/callback"

在处理回调的控制器中,你应该这样做:

client.authorization_code = params[:code] 
access_token = client.access_token! :client_auth_body 
FbGraph::User.me(access_token).fetch

确保你让fb_graph知道你的应用程序的ID和秘密是什么。您应该查看this stackoverflow以确保您的应用信息安全。

我还会插入koala gem