6

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
user2954587
  • 4,661
  • 6
  • 43
  • 101
  • What version of Rails are you using? How are you setting the cookie lifetime? – Old Pro Feb 12 '19 at 22:03
  • @OldPro Rails 5. I'm not setting an expiration / lifetime anywhere which I believe means it doesn't expire. Above is my only cookie code https://stackoverflow.com/questions/7744459/rails-csrf-tokens-do-they-expire – user2954587 Feb 13 '19 at 00:54
  • I think it is ITP https://webkit.org/blog/7675/intelligent-tracking-prevention/. It should also happen on Mac's Safari. I think you should use localStorage. – mogbee Feb 13 '19 at 00:56
  • @mogbee doesn't appear so. The article you linked to talks about 3rd party cookies, this isn't a 3rd party cookie. Even those cookies they say last for >1 day. Mine expires in less than 2 hours – user2954587 Feb 13 '19 at 01:01

1 Answers1

2

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.

Old Pro
  • 24,624
  • 7
  • 58
  • 106