[mod_python] No expiration datestamp on SessionID cookie

Deron Meranda deron.meranda at gmail.com
Wed Sep 27 17:34:56 EDT 2006


On 9/27/06, Sébastien Arnaud <arnaudsj at emedialibrary.org> wrote:
> I have a few webapp running with mod_python, and I just had the
> request to expire a Session when the browser window is closed. I have
> done that in other web framework by NOT setting the expiration of a
> cookie, usually the browser then understand that it needs to destroy
> the cookie when the window/tab is closed.
>
> I am looked through the last 2-3 year on the list and in the current
> 3.2 doc but I can't find anywhere a way to specify the expiration
> date of the SessionID cookie.

If you use the lower-level mod_python Cookie class directly you
can affect all the possible cookie parameters, including the
expires parameter.

To leave off the expiration parameter is simple.

   from mod_python import Cookie
   k = Cookie.Cookie( 'sample', 'value' )
  Cookie.add_cookie( req, k )

The value of the cookie (as with str(k)) will be:
    sample=value

If you want to put an expiration time on it, the only really tricky
part is that the cookie standards don't use ISO-8859 formats.

   from mod_python import Cookie
   import datetime

   now = datetime.datetime.uitcnow()
   expires = now + datetime.timedelta( 1, 0 ) # 1 day
   k = Cookie.Cookie( 'sample', 'value', \
              expires.strftime('%a, %d-%b-%Y %H:%M:%S GMT') )
  Cookie.add_cookie( req, k )

Then str(k) gives somethine like:
    sample=value, expires=Wed, 27-Sep-2006 21:17:16 GMT


If you're wanting for force cookies to expire (for security reasons),
note that relying on the expired parameter (or the lack thereof)
is not very good.

What I do is to use a SignedCookie object instead of a plain
Cookie.  Then I format a specific expiration time into the
cookie contents (usually with ISO 8859 UTC format), and
sign the cookie.

When I later extract and use the cookie, I always validate
that the embedded expiration time is still in the future.
In this way I can make sure it is impossible for anybody to
ever artificially extend the life of their cookies.

Note you can do both...embed the expiration time inside a
SignedCookie, as well as omiting the expires= parameter.
Then the cookie will under normal use disappear when the
browser is closed; but you also have a secondary check
that makes sure it can never outlive your intended maximum
cookie lifetime.

Oh, and if you're really secure and want to help avoid some
recent cross-site scripting cookie stealing; also set the secure
cookie parameter (but see Issue #108 as it's not available
in mod_python until very recently)
https://issues.apache.org/jira/browse/MODPYTHON-108

Deron Meranda



More information about the Mod_python mailing list