django-device-bound-sessions
Device Bound Session Credentials (DBSC) for Django. If someone steals a user's session cookie, it stops working on any other device.
How it works
With DBSC, a supporting browser (Chrome) creates a key pair in the device's secure hardware when the server offers registration after a user logs in. The private key never leaves the device. The library adds a second, short-lived "bound" cookie alongside Django's normal session cookie. A browser can only get a new bound cookie by signing a server challenge with that key.
login, then the next page ──► Secure-Session-Registration: (ES256 RS256);path="/dbsc/register/";challenge="…"
browser ──► POST /dbsc/register/ Secure-Session-Response: <JWT signed by the new key, includes its public JWK>
server ◄── 200 session config JSON
Set-Cookie: dbsc_bound=…; Max-Age=600
Secure-Session-Challenge: "<next challenge>";id="<id>"
…bound cookie expires; the browser refreshes it before sending its next request…
browser ──► POST /dbsc/refresh/ Sec-Secure-Session-Id: "<id>"
Secure-Session-Response: <JWT over the cached challenge>
server ◄── 200 Set-Cookie: dbsc_bound=…
Secure-Session-Challenge: "<next challenge>";id="<id>"
There are two cookies. Django's normal sessionid still says who the user is, and stays as long-lived as it always was. dbsc_bound is the short-lived one that proves the request comes from the device that registered; only the refresh endpoint issues it.
The registration offer is sent once, on the first page after login() that isn't a redirect, within OFFER_MAX_AGE (60 seconds).
Every response that sets a bound cookie also sends the next challenge, so a refresh normally takes one request. Refresh challenges stay valid as long as a bound cookie does (BOUND_COOKIE_AGE + BOUND_COOKIE_GRACE). If the browser has no usable challenge, for example because the user was idle for longer than that, the server answers its refresh with a 403 and a fresh challenge, and the browser retries with a proof over it.
Once a Django session is bound, the middleware rejects any request that lacks a valid bound cookie (by default it treats the request as anonymous). An attacker holding only sessionid has no key, so they can't refresh, and are locked out once the bound cookie expires: within BOUND_COOKIE_AGE + BOUND_COOKIE_GRACE seconds (630 by default).
Browsers without DBSC support ignore the registration header. Their sessions never become bound and keep working exactly as they do today.
There is no database model. The device binding (public key, algorithm, and audit fields) is stored in the Django session itself, so:
- it works with any
SESSION_ENGINE(db, cache, cached_db, file, signed_cookies); - it lives exactly as long as the session does. Logging out or flushing the session removes the binding, and the browser's next refresh gets
{"continue": false}.
Installation
Requires Python 3.12+ and Django 5.2 (LTS) or 6.1+.
pip install django-device-bound-sessions
INSTALLED_APPS = [
...,
"django_device_bound_sessions",
]
MIDDLEWARE = [
...,
"django.contrib.sessions.middleware.SessionMiddleware",
...,
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django_device_bound_sessions.middleware.DeviceBoundSessionMiddleware", # after auth
...,
]
# urls.py
urlpatterns = [
...,
path("dbsc/", include("django_device_bound_sessions.urls")),
]
That's it: no migrations. Any django.contrib.auth.login() call offers DBSC registration on the next non-redirect response.
Using it in views
Every request gets request.dbsc:
| attribute | meaning |
|---|---|
request.dbsc.binding |
DeviceBinding for this session, or None |
request.dbsc.session_id |
DBSC session id, or None |
request.dbsc.registered |
the session has a binding |
request.dbsc.bound |
request carried a valid bound cookie |
A DeviceBinding has session_id, algorithm, public_key (JWK), thumbprint (RFC 7638), user_agent, created_at, and last_refreshed_at.
Helpers:
from django_device_bound_sessions.api import get_binding, offer_registration
from django_device_bound_sessions.decorators import dbsc_exempt
offer_registration(request) # offer DBSC outside of login (e.g. after step-up auth)
get_binding(request) # the DeviceBinding, also available as request.dbsc.binding
@dbsc_exempt # skip enforcement and offers for this view
def health(request): ...
To end a binding, end the session (logout(), request.session.flush()).
Type checking
The package ships py.typed and is checked with mypy (strict, with django-stubs), pyright (strict), and ty. You don't have to change how your views are typed. Pick whichever of these fits your code:
from django.http import HttpRequest
from django_device_bound_sessions.api import DBSCHttpRequest, DBSCRequestMixin, get_dbsc_state
# 1. Views typed against plain HttpRequest: nothing to change.
def account(request: HttpRequest) -> HttpResponse:
state = get_dbsc_state(request) # DBSCState
if state.binding is not None:
...
# 2. Use DBSCHttpRequest to access request.dbsc directly.
def account(request: DBSCHttpRequest) -> HttpResponse:
if request.dbsc.bound:
...
# 3. Already have your own request type? Add the mixin to it.
class AppRequest(DBSCRequestMixin, HttpRequest):
tenant: Tenant
If the middleware isn't installed, get_dbsc_state() raises ImproperlyConfigured instead of quietly reporting an unbound session. get_binding(request) reads the session directly and works without the middleware.
typecheck/downstream.py pins these types down for apps using the library. mypy, pyright and ty all check it strictly, so a change that loosens or breaks them fails the check.
Annotate your settings with DBSCConfig to get misspelled keys and wrong value types flagged:
from django_device_bound_sessions.conf import DBSCConfig
DBSC: DBSCConfig = {"BOUND_COOKIE_AGE": 300, "ENFORCEMENT": "anonymous"}
Settings
Set these in a DBSC dict in your settings:
| setting | default | |
|---|---|---|
BOUND_COOKIE_NAME |
"dbsc_bound" |
|
BOUND_COOKIE_AGE |
600 |
seconds; this is how long a stolen bound cookie stays useful |
BOUND_COOKIE_GRACE |
30 |
extra seconds the server accepts after expiry |
BOUND_COOKIE_DOMAIN / _PATH / _SECURE / _HTTPONLY / _SAMESITE |
None / "/" / True / True / "Lax" |
|
ALGORITHMS |
["ES256", "RS256"] |
offered in preference order (none is never accepted) |
CHALLENGE_MAX_AGE |
60 |
seconds a registration challenge is valid, from when the offer is sent. Refresh challenges last as long as a bound cookie (BOUND_COOKIE_AGE + BOUND_COOKIE_GRACE) |
CACHE_ALIAS |
"default" |
cache that makes challenges single-use; must be shared by every worker (see Security notes) |
SCOPE_ORIGIN |
None |
scope.origin |
SCOPE_INCLUDE_SITE |
False |
scope.include_site |
SCOPE_SPECIFICATION |
[] |
e.g. [{"type": "exclude", "domain": "*", "path": "/static"}] |
ALLOWED_REFRESH_INITIATORS |
[] |
|
REGISTRATION_PATH / REFRESH_PATH |
None |
override the URLs (default: reversed from django_device_bound_sessions.urls) |
OFFER_ON_LOGIN |
True |
|
OFFER_MAX_AGE |
60 |
seconds after login() that a registration offer can still be sent |
ENFORCEMENT |
"anonymous" |
"anonymous": treat the request as logged out. "logout": flush the session. "off": check request.dbsc yourself |
Security notes
- A binding is permanent for the life of the session. The first device to register owns the session. Registration is refused (409) on a session that is already bound, so a stolen session cookie can't be used to move the session onto another device. To use a new device, log in again, which creates a new session.
- The window before binding is unprotected, and it's kept short. Until registration completes, whoever holds the session cookie could receive the registration offer. Offers are only sent for
OFFER_MAX_AGEseconds after login and are used once. DBSC can't protect a session that was stolen before it was bound; like the spec, this library assumes the device wasn't compromised at login time. - Challenges are signed with
SECRET_KEYand expire. Each one is accepted once, enforced through the cache. Registration challenges are tied to the Django session that received them. - The cache must be shared by every worker. It's the only state the library keeps outside the session: a record of used challenges, so a signed proof can't be replayed. Use a cache that every process and server sees and that has an atomic
add(), such as Redis, Memcached or Django's database cache, and pointCACHE_ALIASat it. Django's defaultLocMemCacheis per-process, so with several workers a used proof could be replayed on another worker until its challenge expires.DummyCachedisables replay protection entirely, because itsadd()always succeeds. A system check (run bymanage.py check,runserverandmigrate) warns aboutLocMemCache(django_device_bound_sessions.W001, which you can silence withSILENCED_SYSTEM_CHECKSif you only ever run one process) and reports an error forDummyCache(E002) or aCACHE_ALIASthat isn't inCACHES(E001). - A refresh with an invalid proof is rejected, but the DBSC session stays alive. Otherwise anyone holding a stolen cookie could knock the real device off.
- A refresh without the matching Django session (the user logged out, the session expired, or the binding was replaced) returns
{"continue": false}, which tells the browser to stop. It never changes the session it was sent with. - DBSC endpoints are CSRF-exempt, because the browser calls them without a token. The signed challenge authenticates them instead. Responses are
no-storeandX-Frame-Options: DENY.
Testing your app
django_device_bound_sessions.testing.DBSCBrowser wraps a Django test Client and simulates the browser side of DBSC:
from django_device_bound_sessions.testing import DBSCBrowser
def test_private_page(client, user):
browser = DBSCBrowser(client) # or algorithm="RS256"
client.force_login(user)
browser.get("/") # registers automatically
browser.expire_bound_cookie()
assert browser.get("/private/").status_code == 200 # refreshes first, like Chrome
Development
uv sync
uv run pre-commit install # ruff lint + format and zizmor on every commit
uv run pytest
uv run pytest --cov # with line + branch coverage (fails below 95%)
uv run mypy
uv run pyright
uv run ty check
CI (.github/workflows/ci.yml) runs on pushes to main and on pull requests:
- Tests on Python 3.12–3.15 with the latest Django 6.1.x, and Python 3.12–3.14 with the latest Django 5.2.x (LTS).
- Coverage: branch coverage with a 95% floor. The run summary shows the coverage table, and the full HTML report is attached as the
coverage-reportartifact. A separate workflow (pages.yml) publishes the report and the README badge's data to GitHub Pages on pushes tomain. There's also a run against the lowest versions allowed bypyproject.toml(Django 5.2.0, PyJWT 2.10.0). - Pre-commit on every file:
ruff check+ruff format, and zizmor for the workflows and Dependabot config. In CI, zizmor also runs its online audits, such as checking that each pinned action SHA is a real commit in that action's repository. - mypy (strict, with django-stubs), pyright (strict on
src/andtypecheck/) and ty.
A final CI passed job depends on all of these and succeeds only if they all did. It's the one check to require in branch protection, so changing the matrix never means updating the ruleset.
Actions are pinned to commit SHAs. Dependabot or Renovate can keep them up to date.
Run uv run pre-commit run --all-files to lint and format everything by hand. Ruff isn't a project dependency. It runs only through pre-commit, so the hook's rev in
.pre-commit-config.yaml is the single ruff version used locally and in CI.
Demo project
uv run example/manage.py migrate
uv run example/manage.py createsuperuser
uv run example/manage.py runserver
Open http://localhost:8000 in Chrome with DBSC enabled and log in. The home page shows the binding status. The demo's bound cookie lives 60 seconds, and an Expire bound cookie button forces a refresh, which you can watch in DevTools → Application → Device Bound Sessions.
DBSC requires HTTPS, except on localhost.
Protocol reference: https://w3c.github.io/webappsec-dbsc/
Metadata
Release files for django-device-bound-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)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| django_device_bound_sessions-0.1.0.tar.gz | 96.8 kB | With provenance | Details for django_device_bound_sessions-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| django_device_bound_sessions-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for django_device_bound_sessions-0.1.0-py3-none-any.whl |
Total release size: 127.1 kB
Release files / django_device_bound_sessions-0.1.0.tar.gz
| Download URL | django_device_bound_sessions-0.1.0.tar.gz |
|---|---|
| Size | 96.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4191f5f408252d779ce3dea4a0a2e47d8bdabaf324caa8640114051a9f7b29bc
|
|
BLAKE2b-256 checksum How to use checksums |
93ecb20da07a11fc61fe290328842d36e8cb0b55635b12c98c97a139909b6091
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.
Transparency logRelease files / django_device_bound_sessions-0.1.0-py3-none-any.whl
| Download URL | django_device_bound_sessions-0.1.0-py3-none-any.whl |
|---|---|
| Size | 30.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
10fd06b634c18f64d5a64c59d0ed6cb333863a55c4ee2e387c0dc6e163457313
|
|
BLAKE2b-256 checksum How to use checksums |
fa2e7a29a3045d268fc857478fc9ef8bb4ce804aee97d766a583cc1ab5148ab1
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.
Transparency logSecurity for django-device-bound-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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for django_device_bound_sessions-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 7, 2026.
Transparency logA 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.