Secure User Sessions

Compatibility

CPython & MicroPython

Required Microdot source files

Required external dependencies

CPython: PyJWT
MicroPython: jwt.py, hmac.py

Examples

The session extension provides a secure way for the application to maintain user sessions. The session data is stored as a signed cookie in the client’s browser, in JSON Web Token (JWT) format.

To work with user sessions, the application first must configure a secret key that will be used to sign the session cookies. It is very important that this key is kept secret, as its name implies. An attacker who is in possession of this key can generate valid user session cookies with any contents.

To initialize the session extension and configure the secret key, create a Session object:

Session(app, secret_key='top-secret')

The with_session decorator is the most convenient way to retrieve the session at the start of a request:

from microdot import Microdot, redirect
from microdot.session import Session, with_session

app = Microdot()
Session(app, secret_key='top-secret')

@app.route('/', methods=['GET', 'POST'])
@with_session
async def index(req, session):
    username = session.get('username')
    if req.method == 'POST':
        username = req.form.get('username')
        session['username'] = username
        session.save()
        return redirect('/')
    if username is None:
        return 'Not logged in'
    else:
        return 'Logged in as ' + username

@app.post('/logout')
@with_session
async def logout(req, session):
    session.delete()
    return redirect('/')

The save() and delete() methods are used to update and destroy the user session respectively.