设计 Omniauth-Facebook 可记住

Devise Omniauth-Facebook rememberable

问题

我有 Devise Omniauth-Facebook 身份验证。使用 facebook 登录有效,但当用户转到 localhost:3000 时会话丢失。 我有以下 GEM:

Devise 4.2.0
Rails 5
omniauth 1.4.0
omniauth-facebook 4.0.0
omniauth-oauth2 1.4.0

描述

会话对于未通过 Omniauth-Facebook 身份验证的用户正常工作,

这是我的 devise.rb omniauth-facebook 设置:

config.omniauth :facebook, "APP_ID", "APP_SECRET", callback_url: "http://127.0.0.1:3000/users/auth/facebook/callback", scope: 'public_profile, email', image_size: 'large', provider_ignores_state: true 

我已经尝试了以下无效的解决方案:

  1. 关闭protect_from_forgery
  2. OmniAuth.config.full_host = "http://127.0.0.1:3000"
  3. 遵循以下 Jeroen van Dijk 接受的解决方案 post: Devise and OmniAuth remembering OAuth 对于这个解决方案,在我的 rake 路由中我没有路径 user_oauth_connect_path,即使我在 routes.rb 中添加了路由。我也认为这不是我的问题的解决方案,因为我有 Devise 4.2.0 和 Rails 5
  4. @user.remember_me = 真

之前的所有解决方案均来自以下 Whosebug 讨论:

Omniauth+Facebook lost session

Devise and OmniAuth remembering OAuth

该代码是 Deviseomniauth-facebook 的 github 指南中包含的标准代码 非常感谢你的帮助 法布里齐奥·贝尔托利奥

也许这就是我的问题的解决方案? Facebook 登录现在有效,如果会话未存储,用户可以毫无问题地重新登录。我没有更多关于失去会话的经验,所以我对这个问题没有太大兴趣。

Notice that Devise's RegistrationsController by default calls User.new_with_session before building a resource. This means that, if we need to copy data from session whenever a user is initialized before sign up, we just need to implement new_with_session in our model. Here is an example that copies the facebook email if available:

class User < ApplicationRecord
  def self.new_with_session(params, session)
    super.tap do |user|
      if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"]
        user.email = data["email"] if user.email.blank?
      end
    end
  end
end

Finally, if you want to allow your users to cancel sign up with Facebook, you can redirect them to cancel_user_registration_path. This will remove all session data starting with devise. and the new_with_session hook above will no longer be called.

Omniauth Facebook Gihub page