Security: Flask Cookie-based Session

Oct 18, 2012

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

Pros

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

Cons

  • 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 Flaskfrom simplekv.memory import DictStorefrom flaskext.kvsession import KVSessionExtension# a DictStore will store everything in memory# could try MemcacheStore as wellstore = DictStore()app = Flask(__name__)# this will replace the app's session handlingKVSessionExtension(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 NdbStoreclass 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+https://github.com/mbr/simplekv.git instead (v0.6)

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.