刷新用户 facebook 令牌

Refreshing user facebook tokens

我在 rails 中有一个主要基于 facebook oauth2 的应用程序。一目了然 - 用户使用 FB connect 登录并可以列出其页面(并使用该数据做一些事情,但现在这并不重要。我们只关注登录和获取页面列表)。

登录后,我将用户 access_tokenexpires_at 保存在数据库中。然后,每次我需要以用户身份向 facebook api 发出请求(以获取他的页面列表)时,我都会检查 expires_at 是否已过去,如果是,我正在续订使用以下代码段的用户令牌:

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

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

    # Save the new token and its expiry over the old one
    self.facebook_auth = {
      uid:          uid,
      access_token: new_token['access_token'],
      expires_at:   Time.now + new_token['expires'].to_i
    }
    save
  end

这在大多数情况下都有效,但有时我的代码会抛出:

type: OAuthException, code: 190, error_subcode: 460, message: Error validating access token: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons. [HTTP 400]

符合exchange_access_token_info

这个错误是我自己的用户抛出的,我可以说我没有更改密码,所以我不确定是什么原因造成的,也不知道我该如何处理后端在项目符号中刷新令牌-证明方式。

非常感谢任何帮助!

首先,我建议您通读 this link 并确定哪种配置对您的应用程序有意义 - 使用短寿命或长寿命或什么。

现在,我不太确定,但我认为您正在考虑将方法 exchange_access_token_info 作为令牌刷新器。如果是这样,情况并非如此!一旦令牌过期,它就没有用了。 exchange_access_token_info 方法简单地获取 短期令牌 (当前处于活动状态)并使用应用程序 ID 和秘密将其转换为长期令牌。

只要明白——

The user access token cannot be extended infinitely again and again without any user's interaction with your app for 60 days.

所以流程很简单-

  • 当用户对您的应用进行身份验证(用户在前端参与)时,您将获得短期令牌
  • 在服务器端,您将令牌的有效期延长至 60 天。
  • 想再次延长令牌有效期? - 重复这些步骤。

希望对您有所帮助!