Junior — Middle
How do methods of storage and authentication confirmation differ when using JWT and server-side sessions?
sobes.tech AI
Answer from AI
JWT (JSON Web Token) and server sessions differ in how they store and verify authentication:
-
Storage:
- JWT: The token contains all necessary information (payload) and is signed by the server. The token is stored on the client (usually in localStorage or cookie).
- Server sessions: The session state is stored on the server (e.g., in memory, database, or cache), and the client only receives a session ID in a cookie.
-
Authentication verification:
- JWT: The client sends the JWT with each request, and the server verifies the signature and extracts data from the token without accessing storage.
- Server sessions: The server finds session data using the session ID and verifies authentication.
-
Features:
- JWT allows scaling applications without shared session storage, as the state is stored in the token.
- Server sessions are easier to manage (e.g., sessions can be easily invalidated), but require centralized storage.
Example of using JWT in Java (pseudo-code):
String token = Jwts.builder()
.setSubject(userId)
.signWith(secretKey)
.compact();
// On request
Claims claims = Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.getBody();
String userId = claims.getSubject();