Skip to main content

simple-sessions

CI Python 3.12+ Apache 2.0 license

Issue a token after sign-in, read the user ID in a route, and revoke the token on sign-out.

What you get

Add session-based authentication to your FastAPI app with a few lines of code. Your app checks who’s signing in. Once you have their user ID, simple-sessions takes care of issuing, looking up, and revoking their session.

  • CookieAuth sets a cookie that the browser sends with later requests.
  • BearerAuth reads a token that an API client sends in the Authorization header.

Both keep the session on the server. The client gets a random token, and the store keeps its SHA-256 digest. Pick the type your app already uses for user IDs: int, str, or UUID.

Cheat sheet

Add the package to your Python 3.12+ project:

uv add simple-sessions

With pip, run python -m pip install simple-sessions in your virtual environment.

Create one manager for your app. Here our user IDs are integers:

from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException, Request, Response
from pydantic import BaseModel

from simple_sessions import CookieAuth

app = FastAPI()
auth = CookieAuth[int]()


class UserLogin(BaseModel):
    login: str
    password: str

In the login route, use your app’s credential check. Here, verify_credentials stands for a function that returns the verified account’s ID, or None if the credentials are wrong:

@app.post("/login", status_code=204)
async def login(credentials: UserLogin, request: Request, response: Response):
    user_id = await verify_credentials(credentials)
    if user_id is None:
        raise HTTPException(status_code=401)
    await auth.login(request, response, user_id=user_id)

login sets a Secure, HttpOnly cookie and replaces the session from the previous cookie, if present. To protect a route, ask for auth.current_user. FastAPI documents the cookie in OpenAPI, and the handler gets the user ID. A missing or expired session returns HTTP 401.

@app.get("/protected")
async def protected(user_id: Annotated[int, Depends(auth.current_user)]):
    return {"user_id": user_id}


@app.post("/logout", status_code=204)
async def logout(request: Request, response: Response):
    await auth.logout(request, response)

Want to try the whole flow? The runnable example includes a single-account credential check. From the repository root, start the example with uv:

ADMIN_LOGIN=alice ADMIN_PASSWORD=local-demo uv run uvicorn examples.readme.app:app

With pip, install the checkout and Uvicorn using python -m pip install -e . uvicorn, then run the same command without uv run.

In another terminal, send the same Origin that a browser would send on login and logout. Save the cookie from the first response and try it again after signing out:

url=http://localhost:8000
curl -i -c cookies.txt -H "Origin: $url" -H 'Content-Type: application/json' \
  -d '{"login":"alice","password":"local-demo"}' "$url/login"       # 204
curl -i -b cookies.txt "$url/protected"                            # 200
curl -i -b cookies.txt -H "Origin: $url" -X POST "$url/logout"     # 204
curl -i -b cookies.txt "$url/protected"                            # 401

Using a shared router

If you keep your routes in a shared router, set app.state.auth = auth when you create each app. Then put the following dependency in your dependencies.py module. Each request uses its own app’s manager:

from typing import Annotated

from fastapi import Depends, Request

from simple_sessions import CookieAuth


def get_auth(request: Request) -> CookieAuth[int]:
    return request.app.state.auth


type CurrentUser = Annotated[int, Depends(CookieAuth.user_dependency(get_auth))]

Import CurrentUser in your routes and use it as the parameter type: async def protected(user_id: CurrentUser). If you use a custom cookie name, pass the same cookie_name to user_dependency so OpenAPI shows the right name.

Bearer-based authentication

For a CLI or API client, create a BearerAuth manager. After the same credential check as above, issue a token and return it to the client:

from simple_sessions import BearerAuth

bearer = BearerAuth[int]()


@app.post("/token")
async def token(credentials: UserLogin, response: Response):
    user_id = await verify_credentials(credentials)
    if user_id is None:
        raise HTTPException(status_code=401)
    issued = await bearer.sessions.issue(user_id)
    response.headers["Cache-Control"] = "no-store"
    return {"access_token": issued.token, "token_type": "bearer"}


@app.get("/me")
async def me(user_id: Annotated[int, Depends(bearer.current_user)]):
    return {"user_id": user_id}

Send Authorization: Bearer <access_token> on each protected request. To sign out, send the same header to a route that calls await bearer.logout(request).

Other features

Let guests in

A feed can welcome guests and still show signed-in users their own content. Use the cookie manager from the quickstart:

@app.get("/feed")
async def feed(request: Request):
    user_id = await auth.resolve_user(request)
    if user_id is None:
        return {"feed": "public"}
    return {"feed": "personal", "user_id": user_id}

Set a lifetime and check when a session expires

Sessions last one hour by default. For a 15-minute session, pass the lifetime in seconds when you issue it. In the cookie login route, after checking the credentials:

await auth.login(request, response, user_id=user_id, ttl=900)

For the bearer token route, use issued = await bearer.sessions.issue(user_id, ttl=900). To show a signed-in user how long their session lasts, read the session itself:

@app.get("/session")
async def session_details(request: Request):
    session = await auth.require_session(request)
    return {"created_at": session.created_at, "expires_at": session.expires_at}

Share sessions across workers

The default store lives in one process and starts empty after a restart. To share sessions across workers, point them at the same Redis 7+ primary and use the same namespace. Add Redis support to your project:

uv add 'simple-sessions[redis]'

With pip, run python -m pip install 'simple-sessions[redis]'.

Set REDIS_URL to your Redis connection URL. This example creates one client per worker and closes it at shutdown. The shared router above can pick up the manager through get_auth:

import os
from contextlib import asynccontextmanager

from fastapi import FastAPI
from redis.asyncio import Redis
from redis.asyncio.retry import Retry
from redis.backoff import NoBackoff

from simple_sessions import CookieAuth, Sessions
from simple_sessions.redis import RedisSessionStore


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with Redis.from_url(
        os.environ["REDIS_URL"],
        socket_connect_timeout=2,
        socket_timeout=2,
        retry=Retry(NoBackoff(), 0),
    ) as client:
        store = RedisSessionStore(
            client, namespace="my-app:prod", encode_user_id=str, decode_user_id=int
        )
        app.state.auth = CookieAuth(Sessions(store))
        yield


app = FastAPI(lifespan=lifespan)

Have your own store? Implement create, get, and revoke as described in SessionStore.

For more on cookie origins, expiry, and Redis setup, read the English tutorial or the Russian tutorial.

Metadata

Release files for simple-sessions 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for simple-sessions 0.1.0
File Size Uploaded Provenance Actions
simple_sessions-0.1.0.tar.gz 117.5 kB Without provenance Details for simple_sessions-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for simple-sessions 0.1.0
File Interpreter ABI Platform Actions
simple_sessions-0.1.0-py3-none-any.whl Python 3 none any Details for simple_sessions-0.1.0-py3-none-any.whl

Total release size: 136.4 kB

Release files / simple_sessions-0.1.0.tar.gz

Download URL simple_sessions-0.1.0.tar.gz
Size 117.5 kB
Tags Source
SHA-256 checksum
How to use checksums
e419198c0fc7207a2bb91ad6e79f395ca60af08513ee376df16386d4d73494e8
BLAKE2b-256 checksum
How to use checksums
be4c77d44a121a1f43ff1a16d2dc62ae69fcdf77cec5a51bc95b9447bc5c5b81
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.24 {"installer":{"name":"uv","version":"0.11.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / simple_sessions-0.1.0-py3-none-any.whl

Download URL simple_sessions-0.1.0-py3-none-any.whl
Size 18.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ce243708f17b6ae3ad30d405fe3e93cdbfb5f1df502b66d02843f19a9b569136
BLAKE2b-256 checksum
How to use checksums
e752f7c727cc638cc792969a706f05439caa29d66526aa0c523b61086905d57a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.11.24 {"installer":{"name":"uv","version":"0.11.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for simple-sessions 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page