【问题标题】:Renew Facebook access token with Koala使用考拉更新 Facebook 访问令牌
【发布时间】:2012-02-18 04:24:46
【问题描述】:

我在 Ruby on Rails 应用程序上使用 Koala gem

我在通过考拉使用数据的模型上有以下代码:

@graph = Koala::Facebook::GraphAPI.new(token_secret)
friends = @graph.get_connections("me", "friends")

其中token_secret 来自我的users 表的一个字段,保存在登录时。

它工作正常,但几分钟后我得到:

Koala::Facebook::APIError (OAuthException: Error validating access token: Session has expired at unix time 1327438800. The current unix time is 1327442037.):

我找到了使用Facebook JS SDK 中的方法在前面更新此令牌的方法,但是在控制器上调用了我获取朋友列表的这个方法。

如何使用考拉更新token_secret?这可能吗?

【问题讨论】:

标签: ruby-on-rails-3 koala facebook-javascript-sdk


【解决方案1】:

如果您尝试获取 Facebook 网站应用程序的 oauth_token,则需要使用基于重定向的 Oauth 流程。这有点复杂。对于画布应用程序,它更简单。您仍然可以对画布应用使用基于重定向的流程,但最好从 signed_request 中解析它。

每次用户在 Facebook 中加载您的应用时,他们都会使用“signed_request”参数进入您的首页。此加密字符串必须在您的控制器中使用 Koala 对象进行解析。从结果中,您可以获得一个新的 oauth_token,它应该在大约两个小时内有效。这是我的做法。

 #Create a new koala Oauth object.
 oauth = Koala::Facebook::OAuth.new(APP_ID, APP_SECRET) 

 #Get the new oauth_token from the signed request.
 your_new_oauth_token = oauth.parse_signed_request(params[:signed_request])["oauth_token"]

【讨论】:

  • 这就是问题所在,应用程序没有在 Facebook 中加载,它只是一个使用 Facebook 登录的 Web 应用程序,有时我使用 koala 来检索朋友列表,但如果我没有加载任何我的应用程序上的其他页面,但令牌未更新的friends 页面,因为我通过JS 上的FB.getLoginStatus(...) 执行此操作
【解决方案2】:

我想我会回答这个问题,因为这是我刚遇到需要做的事情。

考拉前段时间增加了对交换访问令牌的支持,这里: https://github.com/arsduo/koala/pull/166

所以我的用户模型现在有如下内容:

def refresh_facebook_token
  # Checks the saved expiry time against the current time
  if facebook_token_expired? 

    # Get the new token
    new_token = facebook_oauth.exchange_access_token_info(token_secret)

    # Save the new token and its expiry over the old one
    self.token_secret = new_token['access_token']
    self.token_expiry = new_token['expires']
    save
  end
end

# Connect to Facebook via Koala's oauth
def facebook_oauth
  # Insert your own Facebook client ID and secret here
  @facebook_oauth ||= Koala::Facebook::OAuth.new(client_id, client_secret)
end

【讨论】:

  • 我会试试那个,看起来很不错。但在我尝试之前,我还有几个问题: 1. 我正在使用 Graph API @graph = Koala::Facebook::API.new(accessToken)... 我可以在那里使用 exchange_access_token_info 还是必须使用 Koala::Facebook::OAuth 代替?
  • exhange_access_token_info 是在 Koala::Facebook::OAuth 上定义的,所以是的,你必须在那里使用它。
  • 我想指出,在上面的代码中(当我刚刚用 koala 1.6.0 运行它时),new_token['expiry'] 是一个整数秒的字符串,直到令牌过期......如果您保存令牌,您可能希望将其转换为令牌过期的时间。像 (Time.now + new_token['expires'].to_i) HTH
  • 你能解释一下你从哪里得到 token_secret 吗?我将 auth.credentials.token 保存到用户字段中并尝试将其传递,但​​我相当确定您的 token_secret 是另一回事
  • @MichaelLiu 不是 - 这是同一个令牌。
猜你喜欢
  • 1970-01-01
  • 2016-11-28
  • 1970-01-01
  • 2013-09-12
  • 1970-01-01
  • 2013-10-14
  • 1970-01-01
  • 1970-01-01
  • 2014-09-13
相关资源
最近更新 更多