/fastapi-session

A secured session manager with multiple backends for FastAPI

Primary LanguagePythonMIT LicenseMIT

Fastapi Session

An opinionated fastapi session manager with multiple backends

Notice:

Please, keep in mind that this library is still under heavy development. So changes of any type may happend. The main branch is almost stable most of the time. However, it is better to stick with release tags in order to mitigate error catching. Covering the project with tests takes one of the first places during development. However, it is not much time to test more thoroughly, so, please, be patient if something doesn't work properly or you faced with the outdated documentation or examples. BTW, new issues and pull requests are always welcome :)

Requirements

Features

  • Support multiple type of backends out-of-the-box
  • Support integration with a custom backend
  • Tightly intergrated with FastAPI
  • Focused on a token security and privacy

Supported backends

Backend Support
filesystem + portalocker yes
database No
redis Yes

Installation

Install the package with poetry:

$ poetry add git+ssh://git@github.com:TheLazzziest/fastapi_session.git#0.6.6

Startup

Create a fernet token (signer)

from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

...
secret = "fastsession"
signer = Fernet(
    b64encode(
        PBKDF2HMAC(
            algorithm=hashes.SHA256(),
            length=32,
            salt=salt,
            iterations=100,
        ).derive(secret_key.encode("utf-8"))
    )
)

Connect the session to an app

connect(
    app=app,
    secret=secret,
    signer=signer,
    on_load_cookie=callback
)

Examples

There are some examples of the library usage with the following backends:

Sources