3

I'm having an issue with my application on Heroku where sessions aren't persisting. Specifically, flask's SecureCookieSession object is empty, every time a request is made. Contrast this with running my application on localhost, where the contents of SecureCookieSession persist the way they should.

Also I'm using flask-login + flask-seasurf, but I'm pretty sure the issue happening somewhere between flask / gunicorn / heroku.

Here are three questions that describe a similar issue:

  1. Flask sessions not persisting on heroku
  2. Flask session not persisting
  3. Flask-Login and Heroku issues

Except I'm not dealing with AJAX or multiple workers here (it's a single heroku free dyno, with a single line in the Procfile). I do get the feeling that using server side sessions with redis or switching from Heroku to something like EC2 might solve my problem though.

Also, here's my git repo if it helps https://gitlab.com/collectqt/quirell/tree/develop. And I'm testing session stuff with

def _before_request(self):
    LOG.debug('SESSION REQUEST '+str(flask.session))

def _after_request(self, response):
    LOG.debug('SESSION RESPONSE '+str(flask.session))
    return response
Community
  • 1
  • 1
kai
  • 1,288
  • 3
  • 12
  • 24

2 Answers2

4

Got the solved with some external help, mainly by changing the secret key to use a random string I came up with, instead of os.urandom(24)

Changing to server side redis sessions helped too, if only by making testing simpler

kai
  • 1,288
  • 3
  • 12
  • 24
  • What was the secret key before you replaced with `os.urandom(24)` ? IIRC flask has SecureCookie backend. – amirouche Jun 01 '15 at 00:46
  • I changed **from** `os.urandom(24)` **to** a random string that I typed, sort similar to `AAAAAAAaaaaaa!!!!!!`. (although obviously the secret key in production looks nothing like that) I have a feeling that what os.urandom(24) was generating was breaking heroku's version of hmac Also yes, flask uses SecureCookie – kai Jun 01 '15 at 00:54
  • 2
    I did the same mistake before. If you put `SECRET_KEY = os.urandom(24)` in `settings.py` or something. The key will change every time (hopefuly ;) the (dev?) server restarts and it will make the cookie invalid because the token (secure hash of cookie's key/value pairs) can not be validated with the new secret key. In this case, flask reset the cookie, so it appears empty. http://lucumr.pocoo.org/2013/11/17/my-favorite-database/ might be helpful. – amirouche Jun 01 '15 at 02:19
1

Just in case someone else comes across this question, check APPLICATION_ROOT configuration variable. I recently deployed a Flask application to a subdirectory under nginx with a reverse-proxy and setting the APPLICATION_ROOT variable broke Flask's session. Cookies aren't being set under the correct path because of that.

Derlin
  • 9,572
  • 2
  • 32
  • 53
lukecampbell
  • 14,728
  • 4
  • 34
  • 32