Security: Flask Cookie-based Session

October 17, 2012

Flask decide to store all session variables in the cookie [1] (not just the session id).


  • Less overhead on Server (not IO involved on server-side)
  • No server dependency (different way of storing session: file, memcache, db, etc.)


  • Cookie size limit: not more than 4K
  • Bandwidth round-trip: bouncing a cookie with all the session data in it kinda waste bandwidth
  • Security risk: If the flask’s SECRET_KEY is compromised, all the session variable (especially user id) could be manipulated.

Server-side Session

I am a slightly more conservative and traditional coder, so I would still prefer a server-side session (only session_id stored in cookie).

Luckily, there is Flask-KVSession.

from flask import Flask
from simplekv.memory import DictStore
from flaskext.kvsession import KVSessionExtension

# a DictStore will store everything in memory
# could try MemcacheStore as well
store = DictStore()
app = Flask(__name__)

# this will replace the app's session handling
KVSessionExtension(store, app)

Google App Engine

For GAE, I will utilize the NdbStore for the simplekv implementation (GAE’s ndb has built-in caching).

from simplekv.gae import NdbStore

class Session(ndb.Model):
    v = ndb.BlobProperty(indexed=False)

store = NdbStore(Session)

2012-10-18: pip install simplekv install v0.5 (with no gae support). Use pip install git+ instead (v0.6)

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.