Repository navigation
Session and Token Lifecycle
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
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.
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.
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.
- 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
- Lifecycle at a Glance
- Create: Session IDs
- Transport: Cookie Attributes
- Rotate: On Login & Privilege Change
- Expire: Idle & Absolute Timeouts
- Terminate: Logout & Account Events
- Refresh Tokens: Rotation & Reuse Detection
- Revocation & Introspection
- Verification Tests
| 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 |
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).
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']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 oneIn 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).
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- Logout deletes the server-side session, then clears the cookie (
Max-Age=0). Clearing the cookie alone is not logout: insession-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).
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"] = TrueAlso 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.
| 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).
| 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.
- OWASP Session Management Cheat Sheet
- OWASP ASVS 5.0.0: V3.3 Cookie Setup, V7 Session Management, V10.4
- RFC 9700 ยง4.14 ยท RFC 7009 ยท RFC 7662
- OWASP CSRF Prevention Cheat Sheet
- OAuth & OIDC implementation
- Token theft & session revocation: AiTM cookie theft and per-provider revocation
- OWASP Top 10:2025 A07
- README.md - Web Application Security index
-
labs/secure-api/impl/fixed_api.py -
login,_session,logout,token_refresh - labs/secure-api/README.md - Lab cases and CI evidence
โฌ ๏ธ 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
- ๐บ๏ธ Browse by Topic
- ๐ All Repository Files
- ๐งญ Learning Paths
- ๐ Master Guide
- ๐ค Glossary
- โ๏ธ Legal & Disclaimer
๐ Foundations & Learning
๐ก๏ธ Defense & Investigations
- Incident Response
- Open Source Intelligence (OSINT)
- Reverse Engineering
- Operations Security (OPSEC)
- Compliance
โ๏ธ Platforms & Infrastructure
๐ก Hardware, Wireless & Field Projects
- PNWC Cyberdeck
- Hardware Testing
- Hardware Hacking
- Software-Defined Radio
- Wardriving
- uConsole
- Space Security
๐งฐ Assessment & Field Reference
๐ฆ Downloads & Project Resources
๐๏ธ Additional Topics