DEV Community

Cover image for JWT vs Session Authentication
Royal Jain for CodeParrot

Posted on

JWT vs Session Authentication

Authentication vs Authorization

What exactly is authentication, and how does it differ from authorization? Authentication is the process of verifying who someone is, whereas authorization is the process of verifying what specific applications, files, and data a user has access to. How do you ensure that the person requesting access to a resource is who they claim to be? And once their identity is confirmed, how do you control what they can do or see?

JWT vs. Session Authentication - The Basic Differences

The debate between JWT (JSON Web Token) and Session-Based Authentication is a important point in modern web development.

  • JWT Authentication: Here, the server generates a token that the client stores and presents with each request. It's a stateless method, meaning the server doesn't need to keep a record of the token.

  • Session-Based Authentication: Contrarily, it's stateful. The server creates a session for the user and stores session data on the server-side. The client holds only a session identifier, typically in a cookie.

What is JWT?

JSON Web Token (JWT) serves as a compact and self-contained mechanism for securely transmitting information between parties as a JSON object.

enter image description here

JWT Structure:

  • Header: Specifies the token type (JWT) and the signing algorithm (e.g., HMAC SHA256).
  • Payload: Contains the claims, which are statements about an entity (user) and additional metadata.
  • Signature: Created by encoding the header and payload with a secret, ensuring the token’s integrity.

jwt_dia

JWT in Action:

  • Upon user authentication, the server generates a JWT.
  • This JWT is sent back to the client and stored, often in local storage or an HTTP-only cookie.
  • The client includes this token in the HTTP Authorization header for subsequent requests.
  • The server validates the token and grants access if valid.

Advantages:

  • Scalability: Due to their stateless nature, JWTs are ideal for distributed systems.
  • Flexibility: They can be used across different domains and applications.
  • Security: When properly implemented, they provide a secure way to handle user authentication.

Security Concerns:

  • Transmission Security: It's vital to transmit JWTs over HTTPS.
  • Storage: Store JWTs securely to prevent XSS attacks and other vulnerabilities.

Handling Token Expiry:

  • Implement short-lived JWTs and use refresh tokens for renewing access without re-authentication.

Understanding Session-Based Authentication

Session-based authentication, often referred to as cookie-based authentication, is a method where the server plays a pivotal role in maintaining user authentication records.

How it works:

  1. User Authentication: The user provides credentials, which the server verifies.
  2. Session Creation: Upon successful authentication, the server creates a session record with a unique identifier, user identifier, session start time, expiry, and possibly additional context like IP address and User Agent. Stores that in Database.
  3. Cookie Storage: This session identifier is sent back and stored as a cookie in the user’s browser.
  4. Session Validation: Each request from the user’s browser includes this cookie, then server validates the session by querying to Database. If valid, the request is processed.

Advantages:

  • Simplicity and Reliability: The server’s session record acts as a centralized truth source, making it straightforward to manage user sessions.
  • Revocation Efficiency: Access can be quickly revoked by deleting or invalidating the session record, ensuring up-to-date session validity.

Disadvantages:

  • Performance Issues at Scale: The dependency on database interactions for every session validation can introduce latency, particularly for high-traffic applications.
  • Latency in Dynamic Environments: In applications with dynamic clients, this latency can impact user experience, making session-based authentication less ideal in such scenarios.

session_dia

Conclusion: Making the Right Authentication Choice

Choosing between JWT and session-based authentication depends on your application's specific needs. If you prioritize statelessness and scalability, JWT might be your go-to. For traditional applications where immediate control over sessions is crucial, session-based authentication holds the upper hand. Understanding these concepts and their implications is key to developing secure and efficient web applications.

Top comments (26)

Collapse
 
adaptive-shield-matrix profile image
Adaptive Shield Matrix

The boundary is much more blurry

  • Both JWT and Session are generated on the server
  • Both JWT and Session have to validated on each request
  • You can store your JWT token in a secure cookie (so javascript has no access to it)
  • Even with JWT you most likely still store "session data" (then a login last happened from which country/ip/device) on the server for security/audit purposes

JWT is more like a data format so you can still do session authentication with JWT

Collapse
 
royaljain profile image
Royal Jain

Valid points. To me main difference is stateless vs stateful and most other differences stem from that very nature.

Collapse
 
ferbs profile image
Jeff Ferber

Both JWT and session cookies can be stateless. Persisting some light state serverside is often worthwhile though, supporting features like a user logging out of a public kiosk from a different device later, or enforcing a short session expiration policy but extending it while in active use. (And can have great performance using Redis or some other k/v store.) But if you really don't want to hit redis, the cookie value can be signed like JWT or fully encrypted.

Collapse
 
ferbs profile image
Jeff Ferber

Good points but I don't think the conclusion is at all blurry. JWT is overused, session cookies are easier to use and more secure. JWT was popularized as an auth workaround for serverless/jamstack and by delegated auth vendors (like auth0) so it seems like a modern/trendy choice to a coder who doesn't look closely, but in reality it's a bad choice in most scenarios. Avoid JWT unless there's a specific and compelling need for it.

Preventing javascript from accessing auth-related secrets is a valuable security feature that session cookies offer with the HttpOnly option. You can lock them down further with the Host, SameSite, and Secure options. Web frameworks like Django/Laravel/Spring/Rails/etc make them even easier to implement. Stuffing JWT into one is fine, but then there's little point to it and in practice they're left insecure.

Collapse
 
prabhat_deshmukh_0d25f7e9 profile image
Prabhat Deshmukh

In what situations would jwt be absolutely required?

Collapse
 
charlesr1971 profile image
Charles Robertson

For those of you, interested, I have created a JWE library:

forgebox.io/view/JWTSignEncrypt

Normally, a JWT is just base64 encoded. A JWE is an encrypted JWT, which makes it virtually impossible to crack.

Collapse
 
shameel profile image
Shameel Uddin

Everything is "virtually impossible to crack" until it is cracked. :D

Collapse
 
charlesr1971 profile image
Charles Robertson

That’s why I was very careful to use the word “virtually”. ;)
The point is that a JWT is easy to inspect, whereas an encrypted JWT is much harder to inspect. However, I must stress that sensitive information should not be sent within a JWT claim, so JWEs are theoretically unnecessary.
The point behind a JWT is that sending a User UUID, is deemed acceptable. Modifying the User UUID value, inside the JWT, will cause the authentication phase of the JWT, on the server, to fail.

So it is preferable to send the User UUID, in a JWT, rather than sending it, as an endpoint param.

Collapse
 
holymark profile image
HOLY MARK

absolutely, but some tends to be difficult, making it much longer to crack

Collapse
 
hectorlaris profile image
Héctor Serrano

Tks by share.

Collapse
 
rodri-oliveira-dev profile image
Rodrigo de Oliveira

This article does a great job of explaining some tricky tech concepts in a way that's easy to understand. It talks about how authentication is about proving who you are, and authorization is about what you're allowed to do or see on a website or app. Then it compares two different ways websites keep track of who you are - one using something called JWT and the other using sessions. The explanation is really clear, making these tech ideas much easier to grasp, especially if you're not already an expert in web security. It's a helpful read for anyone trying to get a handle on how online security works.

Collapse
 
schmoris profile image
Boris

Next blog post: How to store JWTs securely :-)

Collapse
 
royaljain profile image
Royal Jain

Nice suggestion. Onto it, let’s open that can of worms 😅

Collapse
 
adaptive-shield-matrix profile image
Adaptive Shield Matrix

Here that auth0, one of the biggest third party provider says about it
auth0.com/docs/secure/security-gui...

Collapse
 
flimtix profile image
Flimtix

This is a very informative and clear summary of JWT and sessions 👍 keep up the good work!

Collapse
 
dev_geos profile image
Dev Geos • Edited

For me, JWT is most suitable (about securities and reusuability) but more hard to program. Session is more easy.
Most Framework (like Django), supports natively Session authentication, it is suitable for short deadline.

Collapse
 
charlesr1971 profile image
Charles Robertson

Great tutorial. Regarding session based auth, you say:

Performance Issues at Scale: The dependency on database interactions for every session validation can introduce latency, particularly for high-traffic applications.

I think this is probably negligible, because normally a REST API request will be requesting data from the database, anyway? 🤔

Collapse
 
royaljain profile image
Royal Jain

IMO additional database calls will happen only after authentication is done, to prevent DDOS attacks, so would be done sequentially not in parallel.

And one man's negligible might be another man's JIRA ticket :)

Collapse
 
gagiknav profile image
Gagik

This was nice, It really helped me to understand.
Thanks!

Collapse
 
adaptive-shield-matrix profile image
Adaptive Shield Matrix

I'd say the scalability point is moot, without the underlying details on how you do your architecture.
You can use a separate domain, load balancers and servers (or even an edge environment like cloudflare workers) to scale authentication requests. Obviously you will have to configure the right CORS and Content-Security-Policy headers as well.

Without seeing how in practice a concrete solution is implemented -> you can't say if one is more scalable than the other.

Collapse
 
royaljain profile image
Royal Jain

Sure, and if done well monoliths are more scalable than bad microservices. Every article on internet would be "it depends on the situation" but that would be a book not a blog :)

Collapse
 
szalonna profile image
Joe • Edited

What I learnt in the past years using both approach on different apps is that:

  • Use JWT between trusted entities in a trusted environment, e.g. authorising requests between services, create short-living tokens only for the length of possible longest response time.
  • Use session-based authentication where you need to communicate between untrusted sources and store a refresh token to each session with which you can generate the short living tokens to sign the request in the system internally.

Benefits:

  • You can force close a session any time if you detect any abusive or unexpected behaviour of the user or on case of password change, etc. With JWT you should blacklist the token and make a check in every round you use that, which kills the JWT token's "stateless-ness".
  • Exposed JWTs can be used for short time, reduced security risk.
  • You don't need to refresh tokens on UI periodically as it expires. (❤️)
Collapse
 
royaljain profile image
Royal Jain

Very well put. Useful information