Concept
Session Creation
A session should come into existence at a clearly defined point in the application's lifecycle.
An application may create an anonymous, pre-authentication session when a user first visits. This can be useful for maintaining state such as:
CSRF tokens
Shopping carts
Multi-step forms
Temporary preferencesThe more security-critical transition happens when the user successfully authenticates.
At that point, the application should not simply upgrade the existing session ID into an authenticated session.
Before login:
Session ID: anonymous_123
β
User submits valid credentials
β
β Keep anonymous_123 and mark it authenticatedInstead:
Before login:
Session ID: anonymous_123
β
User successfully authenticates
β
Invalidate / regenerate session ID
β
Create:
Session ID: authenticated_987Any state that legitimately needs to survive authentication, such as a shopping cart, should be migrated to the new session rather than preserving the old session identifier.
This directly prevents session fixation. Even if an attacker knew or influenced the pre-authentication session ID, that ID becomes useless once authentication generates a fresh credential.
The second design decision is deciding what information should actually live inside the session.
A session generally needs enough information to identify the authenticated user:
session
β user_id
β authentication state
β session metadataBut storing large amounts of authorization data can create a staleness problem:
User logs in
β
Session stores:
role = admin
permissions = [...]
β
Administrator removes user's privileges
β
Old session still contains:
role = admin
permissions = [...]If the application trusts those cached values without rechecking the current authorization state, the user may retain permissions they should no longer have.
For sensitive or frequently changing permissions, it is often safer to derive authorization from a current trusted source rather than treating data calculated at login as permanently valid.
The principle is:
Session
β establishes who the user is
Authorization
β determines what that user may do nowThose decisions should not become permanently coupled just because the user authenticated earlier.