Skip to content

Session and Token Lifecycle

github-actions[bot] edited this page Nov 29, 2026 · 1 revision

Last reviewed: 2026-11-28

Caution

Authorized use only. Session fixation, cookie replay and refresh-token reuse tests are for your own applications, the local Secure API lab, or a written scope. See LEGAL.md.

Prerequisites: OAuth & OIDC implementation ยท Methodology Phase 4: Authentication & Session Testing

๐ŸŽฏ Purpose

Cover the whole life of a server-side session and of OAuth refresh and access tokens: creation, transport, rotation, expiry, termination and revocation. Each stage has the control, the source and the test.

โš™๏ธ Function

Turns the OWASP Session Management Cheat Sheet, ASVS 5.0.0 V3.3 and V7, and RFC 9700 ยง4.14 into implementation rules. The code is from the lab's impl/fixed_api.py, plus a stdlib cookie checker for CI.

๐Ÿ† Goal

Session IDs and refresh tokens are unguessable, change at every login, expire on the server, and stop working at logout or when reused. CI asserts each of these.

๐Ÿ“‹ When To Use

  • Implementing login, logout, "remember me" or token refresh
  • Choosing cookie attributes or deciding where a browser app keeps tokens
  • Setting idle and absolute timeouts
  • Reviewing a session fixation, cookie or token replay finding

๐Ÿ“‹ Table Of Contents

Lifecycle at a Glance

Stage Control Source Lab case
Create CSPRNG reference token, at least 128 bits of entropy ASVS 7.2.3 -
Transport __Host- prefix, Secure, HttpOnly, SameSite, Path=/ ASVS 3.3.1-3.3.4 session-cookie-attributes
Rotate New ID on login and re-authentication; old one terminated ASVS 7.2.4 session-rotation-on-login
Expire Server-side inactivity and absolute timeouts ASVS 7.3.1, 7.3.2 session-idle-timeout
Terminate Logout invalidates the server-side session ASVS 7.4.1 session-logout-server-side
Refresh Rotation with reuse detection, or sender-constraining RFC 9700 ยง4.14.2; ASVS 10.4.5 refresh-token-rotation-reuse

Create: Session IDs

The OWASP cheat sheet sets a floor of 64 bits of entropy. ASVS 7.2.3 asks for at least 128 bits for reference tokens. Use the higher figure. The lab uses 256 bits:

sid = secrets.token_urlsafe(32)  # 256 bits from the CSPRNG
  • Generate IDs on the server only. Never accept a client-chosen ID, and never derive one from the user ID, time or a counter.
  • Verify the session on a trusted backend (ASVS 7.2.1). Session state lives on the server; the cookie is only a reference.
  • Do not use static API keys as session tokens (ASVS 7.2.2).

Transport: Cookie Attributes

The OWASP cheat sheet calls Secure and HttpOnly mandatory for session IDs and recommends the __Host- prefix, which requires Secure, Path=/ and no Domain attribute. It says to treat SameSite as defense in depth against CSRF, "not as a replacement for a CSRF token". The fixed lab cookie:

Set-Cookie: __Host-sid=<value>; Path=/; Secure; HttpOnly; SameSite=Strict

Do not store session IDs, access tokens, refresh tokens or JWTs in localStorage or sessionStorage. The cheat sheet's reason is that any script in the origin can read them, so one XSS flaw discloses every token. For single-page apps, keep tokens on a backend-for-frontend and give the browser only a session cookie (ASVS 10.1.1).

This stdlib checker can run in CI against every Set-Cookie header your test client receives:

REQUIRED = {"secure", "httponly", "path=/"}

def cookie_problems(set_cookie: str) -> list[str]:
    """Check one Set-Cookie value against ASVS 3.3.1-3.3.4 for a session cookie."""
    name_value, *attrs = [p.strip() for p in set_cookie.split(";")]
    name = name_value.split("=", 1)[0]
    lowered = {a.lower() for a in attrs}
    problems = [f"missing {a}" for a in sorted(REQUIRED - lowered)]
    if not name.startswith("__Host-"):
        problems.append("name lacks the __Host- prefix")
    if not lowered & {"samesite=strict", "samesite=lax"}:
        problems.append("SameSite is not Strict or Lax")
    if any(a.startswith("domain=") for a in lowered):
        problems.append("__Host- cookies must not set Domain")
    return problems

assert cookie_problems("__Host-sid=abc; Path=/; Secure; HttpOnly; SameSite=Strict") == []
print(cookie_problems("sid=abc; Path=/"))
# ['missing httponly', 'missing secure', 'name lacks the __Host- prefix', 'SameSite is not Strict or Lax']

Rotate: On Login & Privilege Change

The cheat sheet: "The session ID must be renewed or regenerated by the web application after any privilege level change", and regeneration at login is mandatory to prevent session fixation. ASVS 7.2.4 adds re-authentication and asks that the current token is terminated. From the lab's login:

self.sessions.pop(req.cookies.get(SESSION_COOKIE, ""), None)   # forget the pre-login ID
sid = self._new_session(user["id"])                             # issue a fresh one

In session-rotation-on-login, a session ID planted before login was authenticated afterwards on the vulnerable twin (200) and refused on the fixed twin (401).

Expire: Idle & Absolute Timeouts

Enforce both timeouts on the server; a cookie Max-Age alone is not a timeout. The cheat sheet's common ranges are 2-5 minutes idle for high-value applications, 15-30 minutes for low-risk ones, and 4-8 hours absolute for an application used for a full office day. ASVS 7.1.1 asks that the chosen values are documented and justified. The lab uses 15 minutes idle and 8 hours absolute:

if now - session["last_seen"] > IDLE_TIMEOUT or now - session["created"] > ABSOLUTE_TIMEOUT:
    del self.sessions[sid]
    return None
session["last_seen"] = now

Terminate: Logout & Account Events

  • Logout deletes the server-side session, then clears the cookie (Max-Age=0). Clearing the cookie alone is not logout: in session-logout-server-side, the vulnerable twin still accepted a cookie saved before logout.
  • Terminate all sessions when an account is disabled or deleted (ASVS 7.4.2), and offer to end other sessions after a password or MFA change (ASVS 7.4.3).
  • Let administrators end a user's sessions (ASVS 7.4.5) and let users see and end their own (ASVS 7.5.2).
  • Require full re-authentication before changing email, phone number, MFA configuration or other account-recovery information (ASVS 7.5.1).

Refresh Tokens: Rotation & Reuse Detection

RFC 9700 ยง2.2.2: "Refresh tokens for public clients MUST be sender-constrained or use refresh token rotation". Under rotation (ยง4.14.2), each refresh returns a new refresh token and invalidates the old one. If an invalidated token is presented again, the authorization server revokes the active one too, because it cannot tell whether the attacker or the client used it first. From the lab's token_refresh:

if record is None or record["family"] in self.revoked_families:
    return json_response(400, {"error": "invalid_grant"})
if record["used"]:
    self.revoked_families.add(record["family"])              # reuse: kill the whole family
    return json_response(400, {"error": "invalid_grant", "error_description": "refresh token reuse"})
record["used"] = True

Also from RFC 9700 ยง4.14.2 and ASVS: bind refresh tokens to the consented scope and resource servers, expire them after client inactivity, give them an absolute lifetime even with sliding expiry (ASVS 10.4.8), and allow revocation on logout or password change.

Revocation & Introspection

Endpoint Behaviour to implement Source
Revocation Accept token and an optional token_type_hint (access_token, refresh_token); answer 200 whether or not the token was valid; unsupported_token_type if that type cannot be revoked RFC 7009 ยง2.1, ยง2.2, ยง2.2.1
Introspection Require authorization of the caller "to prevent token scanning attacks"; always return active; return "active": false with no other details for unknown, expired or revoked tokens RFC 7662 ยง2.1, ยง2.2

Self-contained JWT access tokens cannot be revoked by the resource server alone. Keep their lifetime short, or have resource servers introspect when revocation must take effect at once (ASVS 8.3.2 asks for mitigations when authorization data in tokens may be stale).

Verification Tests

Test Expected
Every Set-Cookie for a session cookie_problems(...) == []
Get an anonymous session ID, log in, reuse the old ID 401
Save the cookie, log out, replay it 401
Advance the clock past the idle timeout (inject a clock; do not sleep) 401
Advance past the absolute timeout while staying active 401
Refresh once, then reuse the first refresh token 400 invalid_grant; the newest token also refused
Disable the user All their sessions and refresh tokens refused

The lab injects a fake clock so the timeout tests run in milliseconds. Its sessions and token families are in-memory dictionaries in one process. A real service needs a shared store, so that logout and reuse detection apply on every instance.

๐Ÿ“š References

See also

Related Files


โฌ…๏ธ Web Application Security index | Master Index | ๐ŸŽฏ Role Navigation | Legal Notice


๐Ÿ“„ Source: WebAppSecurity/session-and-token-lifecycle.md | โœ๏ธ Suggest an edit | โฌ…๏ธ Back to Web App Security

Clone this wiki locally