DEV Community

Discussion on: JWT vs Session Authentication

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 CodeParrot

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?