Managing Token Lifespan with SimpleCookie in Python

You already have a marker that is configured this way:

session_cookie = SimpleCookie() session_cookie['key'] = any_string_value session_cookie['key']["Path"] = '/' headers = [] headers.extend(("set-cookie", morsel.OutputString()) for morsel in session_cookie.values()) start_response(status, headers) 

I can also read the token and extract the necessary information:

 # Get cookies cookies = request.get_cookies() # Get current token from cookies token = cookies['token'].value 

Now, what would be the best way to set the expiration of a cookie, I know that there are two possible keys:

  • session_cookie ['key'] ['max-age'] = "time in secods"
  • session_cookie ['key'] ['expiration'] = "future date"

How can I find out if a token has expired or what could be the best way to manage expired tokens?

Thank you so much!

+7
source share
1 answer

You can find out if the token has expired if the token does not exist when you try to get it.

 token = cookies['token'].value #this will not exist 

The browser deletes the cookie and everything related to it when it expires .

Thus, in many implementations, you can even delete cookies or, for example, log out, but set the user_id cookie expiration date in the past (for example, a negative number).

Now, as I understand it, you need a policy to determine the expired side of the token server, and this can be done by double checking. For example, try to keep a unique identifier for each token and on the server side, when you read the token, try to check if it expired. In addition, the user can manipulate his files to never blindly trust cookies to store significant data or do some simple user_id verification.

Hope I helped.

EDIT

From rfc2109

Max-Age = Delta Seconds Optional. The Max-Age attribute defines the cookie lifetime, in seconds. The delta seconds value is a decimal value, a negative integer. After delta seconds, the client should refuse the cookie. A value of zero means cookie should be immediately canceled.

And from the wiki http cookie

The Expires directive tells the browser when a cookie is deleted. Derived from the format used in RFC 1123, the date is indicated in the form "Wdy, DD Mon YYYY HH: MM: SS GMT", [29] indicating the exact date / time expires. As an alternative to setting the cookie to expire as an absolute date / time, RFC 6265 allows you to use the Max-Age attribute to set the expiration of cookies as an interval of seconds in the future, relative to the time that the browser received the cookie.

I would recommend using max-age, because it eliminates the problems with setting dates, etc. You just calculate the interval.

Reading a little more, I found that max-age is not supported by IE <9, and that means expiration is preferred.

Max-Age vs Expires

This should help; -)

+3
source

All Articles