Omniauth Session expires when browser is closed

只谈情不闲聊 提交于 2019-12-04 20:55:36

问题


In my rails 3 app I use Omniauth for the user authentication part (fb/twitter).

Actually I follow this:

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

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

But, when I close the browser session expires and I need to login again. How can I keep the session for returning users?

Any help would be greatly appreciated!


回答1:


Devise offers this functionality through its Rememberable module. OmniAuth integrates easily with it through the (you'd never guess it) OmniAuth module. It's even mentioned in the second link you posted!




回答2:


What you want is not difficult, you only have to set a permanent cookie when the session is created and then retrieve this value when you set the current user.

In your ApplicationController, just change your current_user method to:

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

And in your SessionsController, modify your create to set the cookie if user wants to:

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



回答3:


Please make sure the cookie policy that your rails app follows does have sensible settings for your use case (see the link in my comment above). All I can imagine right now (knowing what I know, sitting where I sit) is that the cookie(s) ha(s/ve) properties that are suboptimal/undesirable in your context.

Please check the cookie settings in a browser debug/development tool such as firebug, firecookie or the chrome development tools.

Sorry, that's all I can come up with given my knowledge of the problem. Feel free to contact me again with more details on your cookie- and testing-setup.

My 2Cents.



来源:https://stackoverflow.com/questions/9168426/omniauth-session-expires-when-browser-is-closed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!