Simulate session cookies in mobile sessions?

前端 未结 5 1739
清歌不尽
清歌不尽 2020-12-31 04:42

I discovered to my astonishment at the first glance that my thinking of how session cookies behave on mobile devices is overruled by reality.

On normal desktop brows

5条回答
  •  说谎
    说谎 (楼主)
    2020-12-31 05:33

    This problem is not limited to mobile devices. Session cookies may last "forever" also on a desktop browser, if a user constantly chooses to "restore the previous session" (I learned this the hard way).

    A client-side solution to limit sessions to one day is the following:

    Set two cookies:

    • a (browser-)session cookie, and
    • a cookie that expires in the middle of the user's night (e.g., at 4 am or 5 am), between, e.g., 2 hours and 26 hours from when it is set (in general, it should expire in a window btw. x and x+24 hours)

    If EITHER cookie is missing, start a new session and reset them both.

    To set the second cookie, you can make use of Date.getTimezoneOffset(). Alternatively, if you are able to reliably geolocate the user so that you have at least a rough estimate of their longitude, you can use the longitude to calculate when the "middle of the user's night" is expected to be (1 hour is 15 degrees of longitude). Two possibilities are: by IP address (knowing the country may not be enough, though: in countries like the USA you need at least the state level), or by using info provided by the CDN, if you use one.

    Keep in mind that if something MUST expire after a while (e.g., a session on the server), then you cannot rely on cookies, you must check for expiration server-side too.

提交回复
热议问题