What are the security and architectural considerations of using stateless, token based authentication such as JWT instead of traditional server side sessions for an API?
Short answer
Traditional server side sessions require the server to maintain some form of state about each authenticated user, which can complicate scaling an application across multiple servers without shared session storage, whereas a stateless token like a JWT contains all the necessary…
Advertisement
AModel answer
Traditional server side sessions require the server to maintain some form of state about each authenticated user, which can complicate scaling an application across multiple servers without shared session storage, whereas a stateless token like a JWT contains all the necessary claims about the user directly within the token itself, cryptographically signed so the server can verify it has not been tampered with, without needing to look anything up in shared storage at all, though this approach introduces its own considerations, such as how to properly revoke a token before its natural expiration if a user's account is compromised.
$token = JWT::encode(['user_id' => 42, 'exp' => time() + 3600], $secretKey, 'HS256');Real-world example
A mobile app backend API issues a signed JWT to a user after login, letting any of several independent API servers verify the token's authenticity and identify the user directly from the token itself, without needing to check a shared session store on every single request.
Likely follow-ups
- How can you revoke a JWT before its expiration time is reached if necessary?
- What is the tradeoff between a shorter lived access token and a longer lived refresh token?
Related topics