ruby-on-rails - OmniAuth Facebook token 过期错误

标签 ruby-on-rails ruby facebook rubygems omniauth

我正在使用 OmniAuth 在我的应用程序中访问 Facebook。我正在使用 fb_graph gem:https://github.com/nov/fb_graph发布到 Facebook。我在 Heroku 上为此应用程序运行 omniauth-0.3.0。当用户稍后登录时,我在创建用户时保存的 token 会更改。

创建用户代码

    class SessionsController < ApplicationController  
    def create  
     auth = request.env["omniauth.auth"]  
     user = User.find_by_provider_and_uid(auth["provider"], auth["uid"])||           
     User.create_with_omniauth(auth)
       session[:user_id] = user.id  
       redirect_to root_url, :notice => "Signed in!"  
         end 

用户模型是:

  def self.create_with_omniauth(auth)  
    create! do |user|  
    user.provider = auth["provider"]  
    user.uid = auth["uid"]  
    user.name = auth["user_info"]["name"] 
    user.token = auth["credentials"]["token"]
    end
   end

我现在在大约 30% 的用户身上看到这个错误-

 FbGraph::InvalidToken (OAuthException :: 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.)

我看到 OmniAuth 中最近修复了过期 token 问题:

https://github.com/soopa/omniauth/commit/67bdea962e3b601b8ee70e21aedf5e6ce1c2b780

我使用此代码尝试刷新访问 token 。但是,我仍然遇到同样的错误。有人可以指出我所缺少的吗? 有没有其他方法可以让我在每次用户登录时更新 token ?

唯一可行的解​​决方案是在用户每次登录时创建一个新用户(我根本不喜欢这个解决方案):

  def create  
    auth = request.env["omniauth.auth"] 
    user = User.create_with_omniauth(auth)
    session[:user_id] = user.id  
    redirect_to root_url, :notice => "Signed in!"  
  end

谢谢!

最佳答案

您可以在创建 session 时简单地更新 token 。

class SessionsController < ApplicationController  
def create  
  auth = request.env["omniauth.auth"]  
  user = User.find_by_provider_and_uid(auth["provider"], auth["uid"]).tap do |u|
           u.update_attributes(:token => auth["credentials"]["token"]) if u
         end || User.create_with_omniauth(auth)
  session[:user_id] = user.id  
  redirect_to root_url, :notice => "Signed in!"  
end 

关于ruby-on-rails - OmniAuth Facebook token 过期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7628952/

相关文章:

java - 为什么 www.twitter.com 有时使用 InetAddress/getHostAddress() 返回不同的 IP 地址?

ios - Facebook 权限 Facebook SDK for iOS 5

ruby - 一行 if 语句不起作用

ruby-on-rails - cucumber + capybara : Problem with a scenario that redirects the browser outside of my app

ios - "Fatal error: unexpectedly found nil while unwrapping an Optional value"- 将图像发布到 FaceBook

ruby-on-rails - 使用回形针时heroku在哪里存储上传的文件

ruby-on-rails - 在 Ruby on Rails 中命名模型 'date' 中的字段是有问题的还是不好的做法?

ruby-on-rails - ruby rails : How do I add a not null constraint to an existing column using a migration?

iPhone核心数据与Ruby on Rails同步

ruby-on-rails - Rails ActionController::UnknownFormat 错误与 respond_to