【问题标题】:Omniauth Session expires when browser is closed关闭浏览器时 Omniauth 会话过期
【发布时间】:2012-02-06 22:41:45
【问题描述】:

在我的 rails 3 应用程序中,我将 Omniauth 用于用户身份验证部分 (fb/twitter)。

其实我是这样的:

https://github.com/RailsApps/rails3-mongoid-omniauth

https://github.com/RailsApps/rails3-mongoid-omniauth/wiki/Tutorial

但是, 当我关闭浏览器会话时,我需要再次登录。 如何为回访用户保留会话?

任何帮助将不胜感激!

【问题讨论】:

标签: ruby-on-rails session login omniauth


【解决方案1】:

你想要的并不难,你只需要在创建会话时设置一个永久cookie,然后在设置当前用户时检索这个值。

在您的ApplicationController 中,只需将您的current_user 方法更改为:

def current_user
  return unless cookies.signed[:permanent_user_id] || session[:user_id]
  begin
    @current_user ||= User.find(cookies.signed[:permanent_user_id] || session[:user_id])
  rescue Mongoid::Errors::DocumentNotFound
    nil
  end
end

如果用户愿意,在您的SessionsController 中修改您的create 以设置cookie:

def create
  auth = request.env["omniauth.auth"]
  user = User.where(:provider => auth['provider'], 
                    :uid => auth['uid']).first || User.create_with_omniauth(auth)
  session[:user_id] = user.id
  cookies.permanent.signed[:permanent_user_id] = user.id if user.really_wants_to_be_permanently_remembered
  redirect_to root_url, :notice => "Signed in!"
end

【讨论】:

  • 感谢您的回答!我结合了设计并解决了我的问题!
  • 你真的不应该在签名的cookie中使用user_id,正确的方法是在你的用户模型中创建一个remember_me令牌,将它保存在永久cookie中,当你没有当前会话,您可以通过查找 remember_me 令牌来创建一个新会话。如果黑客知道如何绕过 cookie 签名(之前已经完成),那么令牌比更改您的 uid 更难猜测。
【解决方案2】:

Devise 通过其 Rememberable 模块提供此功能。 OmniAuth 通过(你永远猜不到的)OmniAuth 模块与它轻松集成。您发布的第二个链接中甚至提到了它!

【讨论】:

  • Here's 有关与 OmniAuth 集成的 Devise wiki 页面。
  • 维克,你遇到问题了吗?
  • 不完全是麻烦。我认为没有必要使用 Devise。我只想让我的用户使用服务提供商的帐户(例如 Twitter 或 Facebook)登录..
  • 最后我将设计与omniauth结合起来!
【解决方案3】:

请确保您的 rails 应用程序遵循的 cookie 政策确实为您的用例提供了合理的设置(请参阅我上面评论中的链接)。我现在所能想象的(知道我所知道的,坐在我坐的地方)是 cookie 具有在您的上下文中次优/不受欢迎的属性。

请检查浏览器调试/开发工具(例如 firebug、firecookie 或 chrome 开发工具)中的 cookie 设置。

抱歉,鉴于我对问题的了解,这就是我所能想到的。请随时再次与我联系,详细了解您的 cookie 和测试设置。

我的 2 美分。

【讨论】:

【解决方案4】:

这对我来说是这样的:

def google_oauth2
  @user = User.from_google(google_params)

  if @user.persisted?
    @user.remember_me = true
    sign_in @user
    ........
  end
end

There is another way to do it

【讨论】:

    猜你喜欢
    • 2011-04-21
    • 2013-11-17
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    • 2017-01-04
    • 2013-08-11
    相关资源
    最近更新 更多