A cookie based session for flask
relying on Fernet
encrypted cookies.
flask
default session rely on signed cookies. This sometimes is not enough, and encrypted data should be used.
Example : Use cookies to store OAuth2 access tokens without the burden of server side storage.
pip install flask-encrypted-cookies-session
Private key used to encrypt cookies can be generated with python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key())"
# -*- coding: utf-8 -*-
from flask import Flask, session
from flask_encrypted_cookies_session import EncryptedCookieSession
DEBUG = "True"
ENCRYPTED_COOKIES_SECRET_KEY = (
"JNJQuYdaUGr8XBSoZNYF9FC-A7RZ7iFqV_KqrCwYr0s=" # Fernet.generate_key()
)
# To rotate your keys:
# ENCRYPTED_COOKIES_SECRET_KEY = "JNJQuYdaUGr8XBSoZNYF9FC-A7RZ7iFqV_KqrCwYr0s=,Dfo2hCeG-S6CeY-_tgJ33gip9rxC2t8qNK0CM0gZlRk=" # [Fernet.generate_key(), Fernet.generate_key()]
app = Flask(__name__)
app.config.from_object(__name__)
# This will replace the default Flask application session interface with the encrypted
# cookie based session
EncryptedCookieSession(app)
@app.route("/set/")
def session_set():
session["key"] = "value"
return "ok"
@app.route("/get/")
def session_get():
return session.get("key", "not set")
poetry
is used to manage this project.
poe the poet
is used as the task runner of this project. If you don't know what a task runner is, think about an alternative version of a Makefile
.
$ poetry install
$ poe test
$ poe test-py39
The github repository should be used for Issues or contributions.