Conceptual Difference between SESSION and TOKEN based authentication: ANALOGY
While personally I mostly use JWT, in this article we will be doing comparative analysis of both.
Firstly I would be describing both type of authentications briefly with the help of an analogy, for detailed concepts you can read: [sessions] & [tokens]
Sessions:
For sessions, you can imagine that your EMAIL is a CAR, and you (USER) are the car owner. You want your car to be parked in a Parking Lot (Server). There is a VALET (Server) who will handle the authentication task. You give your car to the valet, and he writes down your CAR NUMBER in a DIARY (Server Memory), noting that this car belongs to you and assigns a referral ID.
The valet’s diary contains your referral ID and car number plate. He gives you a ticket (signed cookie), which includes the session ID and a cryptographic signature for verification. Now, whenever you need to access the Parking Lot (Server), you show the ticket. The VALET (Server) verifies the ticket by matching signature and with the information in the diary. If it matches, you are granted access.
Tokens:
Tokens work in a simpler way. Here, the valet guy does not note anything in the diary. Instead, he gives you a ticket but stamps it with a STAMP (JWT SIGNATURE) before handing it over.This STAMP is cryptographically secure and is generated by hashing the header and payload cryptographically, which include the user’s info and metadata, along with a secret key.
This eliminates the need for storing anything in the diary. Whenever you try to access resources, the STAMP plays a crucial role in proving authenticity, as it is cryptographically secured and cannot be tampered with.
SUMMARY:
IN SESSIONS THERE IS INFO ON SERVER, AND ONLY A SESSION ID IS ON THE CLIENT. THE SERVER VERIFIES THE SIGNATURE, THEN ACCESSES INFO FROM ITS STORAGE. IN JWT, ALL INFO IS STORED ON THE CLIENT SIDE WITH A SIGNATURE. THE SERVER JUST MATCHES THE SIGNATURE AND USES THE TOKEN DIRECTLY. THE MAIN DIFFERENCE IS WHERE THE INFO IS STORED, AND WHAT IS SIGNED DEPENDS ON WHAT THE CLIENT CONTAINS.
JWT:
Header + Payload + Secret = Signature
of tokenSession:
SessionID + Secret = Signature
of cookieWhat Cookie Stores?
Sessions = Only the
session_id
(+ optional signature)JWTs = Entire
header.payload.signature
(JWT)Without a signature:
The server blindly trusts the cookie, and any tampering goes unnoticed. May contain changes.With a signature:
The server verifies the signature, ensuring the cookie’s data hasn’t been altered.