All case studies

Sessions that end when they should

Planit Traveler signs people in with tokens in HttpOnly cookies. The hard part was making those sessions stop: after a password change, after a token is used, and for someone who should no longer have access.

Project
Planit Traveler, accounts and permissions
My part
Design, backend, browser client and tests
Built with
Django REST Framework, SimpleJWT, PostgreSQL, React
Status
In production since November 2026

The problem

Moving tokens out of browser storage and into cookies was the easy part. A review of how sessions ended found gaps that a working login page hides:

  • A password reset revoked the refresh tokens on record, but rotated tokens had never been recorded. A session that had refreshed once survived the reset.
  • Changing a password ended only the current device’s session.
  • Two requests presenting the same refresh token at once could both succeed.
  • Deactivated users could still refresh.
  • Sign-in, registration and refresh had no CSRF check, because the framework applies it only to requests that are already authenticated. A form on another site could have signed a visitor into someone else’s account.

Constraints

  • Script injected into a page must not be able to read a token.
  • Cookies are sent automatically, so every state-changing request needs its own proof that it came from the app.
  • Several browser tabs share one cookie jar and may all notice an expired token together.
  • A copy of the database should not contain a usable session.

How it works now

SimpleJWT issues and verifies the tokens. Around it I built the cookie transport, CSRF enforcement, single-use rotation and revocation.

Revocation. Each token carries a claim derived from the user’s current password hash with a keyed HMAC. The server recomputes it on every request and refresh. Any password change, by any route, makes every outstanding token on every device stop matching.

Single use. Spending a refresh token inserts a row that must be unique. The database, not application timing, decides which of two simultaneous refreshes wins. Only token identifiers are stored, never the tokens.

In the browser, concurrent requests share one refresh. If another tab got there first, the client waits briefly for the new cookie and tries once more before ending the session.

  1. You are signed in on two devices. Every token carries a claim derived from the current password hash.
  2. You change your password on the laptop, which gets a new session. The claim the server now expects is different.
  3. The phone’s next request carries the old claim, so both of its tokens are refused although neither has expired.

The lines that decide

Revocation is one comparison, made on every request:

def session_hash(user):
    return salted_hmac(
        SESSION_SALT, user.password,
        algorithm='sha256',
    ).hexdigest()[:32]

def token_matches_user(token, user):
    if user is None or not user.is_active:
        return False
    claim = token.get(SESSION_CLAIM)
    return (isinstance(claim, str) and
            constant_time_compare(
                claim, session_hash(user)))
Matching a token to its user, rewrapped. Python.

There is no list of sessions to delete. A new password produces a new hash, the recomputed value changes, and every older token stops matching. The HMAC is keyed with a server secret, so the value in a token reveals nothing about the password.

Single use relies on a uniqueness rule in the database:

with transaction.atomic():
    spent = record_outstanding(old, user)
    try:
        with transaction.atomic():
            BlacklistedToken.objects.create(
                token=spent)
    except IntegrityError as exc:
        # Another request used it first.
        raise RefreshRejected() from exc

    # only the winner gets here
Spending a refresh token, trimmed. Python.

Two simultaneous requests can both reach the insert. Only one can succeed. The inner transaction is a savepoint, so the losing insert can be caught without breaking the outer one.

Two smaller bugs

A setting that looked on but did nothing. From the first version in May 2025 until August 2026, the settings said to cancel a refresh token once it had been swapped for a new one. Nothing ever swapped it. The refresh endpoint only issued new access tokens, and the code to rotate the refresh token sat commented out. So one refresh token stayed valid for its full seven days, however often it was used. Signing out still cancelled it. I turned rotation on in August, and in the same change cut the sign-in token’s life from an hour to 15 minutes. Later I made each refresh token single use.

Deleting a test account blocked new sign-ups. After I deleted a user, my browser still held that user’s sign-in cookie. Every request, including registering a new account, first tried to match the cookie to its user, failed, and answered 401 before the registration code ran. Clearing cookies fixed it for me, but not for anyone else in that position. Now a token whose user no longer exists counts as signed out, and the sign-in, registration and refresh endpoints don’t read the old cookie at all. Disabled and banned accounts are still refused as before.

Authorization

A trip has an owner, editors and viewers. Owners can edit, share and delete. Editors can change content. Viewers can read. Everyone else is told the trip doesn’t exist.

The check that matters happens late. A save takes the row lock first and evaluates permissions after it, so someone whose access was removed while their request waited is refused.

Public responses are built from a separate, smaller serializer, after a privacy review found an API returning user data that no page needed.

Decisions and tradeoffs

Checking the user on every request
Recomputing the claim means loading the user each time, which gives up the stateless property people choose JWTs for. At this scale, a session that can be ended is worth one indexed lookup.
One forced sign-in
Tokens issued before the change carried no claim. I rejected them outright, so everyone signed in again once, in preference to a migration path that would have kept the old gap open.
HttpOnly has a limit
It stops a script from stealing a token. It doesn’t stop a script from acting as the user while the page is open. That is why rich text is sanitized on the server and a content security policy is in place.
A refused replay is only refused
Presenting a spent refresh token fails, but doesn’t end the rest of that session. Treating a replay as theft would be stricter, and would also sign people out when two tabs collide.

How it was tested

The important tests sign in through real cookies with CSRF enforced, the way a browser does. They include concurrent refreshes of one token, replay after rotation and after logout, and a check that no response body, storage area or script-readable cookie ever contains a token.

Run on 23 November 2026 against the main branch, PostgreSQL 15 and Chromium
SuiteCoversResult
Accounts, permissions and privacy, backendCookies, CSRF, rotation, revocation, rate limits, roles, invitations, private data255 of 255 passed
Token exposure, browserResponse bodies, web storage, readable cookies7 of 7 passed
CSRF, browserCross-site sign-in, refresh, password change, sign-out7 of 7 passed
Rotation and sign-in, browserReplay, sign-out, protected pages, password change6 of 6 passed

Outcome and limits

A password change now ends every other session, refresh tokens work once, and sign-in itself is protected against cross-site requests. It has not had a third-party audit.

Next: The page hid it. The API didn’t.