Search code examples
pythonsessioncherrypy

cherrypy 'tools.sessions.secure' seems to be breaking sessions


I'm developing a cherrypy application on localhost and wrote this to figure out what's going on with sessions.

import cherrypy

class WhyNotSessions(object):

    @cherrypy.expose
    def index(self):
        if 'count' not in cherrypy.session:
            cherrypy.session['count'] = 0
        cherrypy.session['count'] += 1
        return "Session count is %s" % cherrypy.session.get('count')

if __name__ == '__main__':
    conf = {
        '/': {
            'tools.sessions.on': True,
            'tools.sessions.secure': True
        }
    }
    cherrypy.quickstart(WhyNotSessions(), '/', conf)

This works as expected, with count incrementing on reload - as long as I comment out 'tools.sessions.secure': True from conf. I'd like to understand better what's happening here because I intend to use secure sessions in production.


Solution

  • I've just stumbled across this same problem.

    This is because setting 'tools.sessions.secure' to True adds the 'secure' flag to the generated cookie that stores the session id.

    If you are not using HTTPS in CherryPy, this cookie will never be returned in any subsequent requests, and so a new session id will be generated each time.

    Enabling HTTPS in CherryPy fixes the problem. See CherryPy documentation on SSL for how to turn this on.