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.
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 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:
- User Authentication: The user provides credentials, which the server verifies.
- 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.
- Cookie Storage: This session identifier is sent back and stored as a cookie in the user’s browser.
- 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.
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 (24)
The boundary is much more blurry
JWT is more like a data format so you can still do session authentication with JWT
Valid points. To me main difference is stateless vs stateful and most other differences stem from that very nature.
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.
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.
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.
Tks by share.
Everything is "virtually impossible to crack" until it is cracked. :D
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.
absolutely, but some tends to be difficult, making it much longer to crack
Next blog post: How to store JWTs securely :-)
Nice suggestion. Onto it, let’s open that can of worms 😅
Here that auth0, one of the biggest third party provider says about it
auth0.com/docs/secure/security-gui...
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.
This is a very informative and clear summary of JWT and sessions 👍 keep up the good work!
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.
Great tutorial. Regarding session based auth, you say:
I think this is probably negligible, because normally a REST API request will be requesting data from the database, anyway? 🤔
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 :)
This was nice, It really helped me to understand.
Thanks!
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.
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 :)
What I learnt in the past years using both approach on different apps is that:
Benefits:
Very well put. Useful information
I would call it "the confrontation of recent years"
I can’t take either side, but it was interesting to read
Useful!