Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS / Rails mobile session only last an hour

Why do mobile sessions last an hour but desktop don't expire.

I'm simply setting the cookie with:

// app.run
$http.defaults.headers.common['X-CSRF-Token'] = $cookies.get('csrftoken');

This works perfectly fine on desktop (many months) but with mobile it only lasts ~1 hour. Why does this happen? Do you need to set cookies differently on mobile (tested in both safari and chrome for iOS)? It's not because a user closes the tab because you can close and re-open and still have the session.

Finally, what is the solution to this problem to keep users logged in for say 30 days? LocalStorage?

ApplicationController

  protect_from_forgery with: :exception
  after_action :set_csrf_cookie_for_ng

  def set_csrf_cookie_for_ng
    cookies['csrftoken'] = form_authenticity_token if protect_against_forgery?
  end
like image 967
user2954587 Avatar asked Feb 08 '19 00:02

user2954587


1 Answers

If you do not explicitly set the life of a browser cookie by adding Expires=<date> to the Set-Cookie header, the cookie is considered a session cookie and is discarded at what the browser considers the end of the session.

Most desktop browsers have an option to "continue where you left off" which saves and restores your sessions (and session cookies) between runs, so your session cookies can last a long time on the desktop. I cannot find documentation on the iOS browsers but I suspect they are simply closing the sessions and deleting the cookies at some point when they consider you "done".

The solution is to explicitly set the expiration date of the cookie. Due to reported issues with Safari on iOS, I recommend also setting the domain of the cookie. As of Rails 5.2, you can use pass a duration (previously and in the Set-Cookie header, you have to provide a specific timestamp):

cookies[:name] = {
  value: 'a yummy cookie',
  expires: 1.year,
  domain: 'domain.com'
}

See the Rails API docs for more information.

like image 111
Old Pro Avatar answered Sep 20 '22 18:09

Old Pro