JWT vs Session authentication
Learn the differences between session-based and JWT authentication. Explore trade-offs, advantages, and use cases to choose the proper authentication scheme for your apps.
Generally speaking, the first step in using an application is authentication, where the end-user provides their identity credentials to successfully log in. After this step, the identity system (i.e. identity provider, auth server, etc.) knows who the user is and what resources they have access to.
Given HTTP is inherently stateless, each request in a session is independent and doesn't recall information from previous ones. Re-authenticating users for every action is cumbersome and harms the user experience.
Let’s enter Session-based authentication and JWT (JSON Web Tokens) authentication, two popular methods for maintaining authentication state. Each has unique advantages and trade-offs, and the choice between them depends on your application's specific needs. If you're deciding between the two, this guide is here to help.
What is session-based authentication?
Session-based authentication relies on the server to maintain a record of the user's authentication state. By creating and managing sessions, the server enables users to stay logged in and continue interacting with an application without having to re-enter credentials with every request.
How session-based authentication works?
Session creation
- A user authenticates and provides some credentials (e.g., email and password).
- If the credentials are valid, the server creates a persistent record representing that session. The session contains information such as a random string, user identifier, session start time, session expiration time, etc.
- The
SessionID
is stored in the database and returned to the user’s client as a cookie.
Session validation
- The process can be triggered manually by the user (e.g., clicking a tab, refreshing a page) or automatically by the client (e.g., during initial page loads or via API calls with a
SessionID
). - Each subsequent calls sends an HTTP request from the client containing the session cookie to the server.
- The server validates the
SessionID
by consulting the session data stored on the server. - If valid, the server process the request and authorize the user.
How to revoke a session?
Sessions can be invalidated in real time, which is handy in situations where quick access revocation is necessary.
- Uers logout manually: The server deletes the session record, effectively logging the user out.
- Admins force user logout: Admins or systems can terminate specific session by deleting it from database. For instance, during a security breach.
- Sessions expiry: Sessions can automatically expire after a set duration of inactivity, or a fixed time limit.
Advantages of session-based authentication
- Simple and reliable: The session record provides a clear, centralized source, allowing a high degree of trust and making authorization decisions more reliable.
- Real-time revocation: By deleting or invalidating the session record, a user's access can be quickly revoked.
Disadvantages of session-based authentication
- Latency in distributed system: Maintaining session data across multiple servers always requires syncing a session store. This introduces additional latency because the server has to check the session store every time a request is made.
- High resource consumption: Each session takes up server resources, impacting performance when the user base scales.
- Security risk: Session hijacking (via stolen session cookies) can allow unauthorized access to user accounts.
- Limited use for APIs: Session-based authentication isn’t great for mobile apps. It stores session data on the server, which can increase load and complexity with a lot of users. Plus, it uses cookies, which are harder to handle on mobile devices.
What is JWT authentication?
JSON Web Tokens (JWTs) take a different approach by embedding all relevant user information directly into a token, using a JSON object. Unlike session-based methods, JWTs are stateless, meaning the server doesn’t manage authentication records.
How JWT authentication works?
A JWT consists of three parts: a header, payload, and signature.
- The header contains the signing algorithm (e.g., HS256) and the token’s type (JWT).
- The payload contains core claims, such as the user's identity, user role, and expiration time.
- The signature uses a key to sign the header and payload, allowing verification of whether the signature has been tampered with.
JWT issuance
- The client sends user credentials to the authentication server (A universal identity provider is particularly beneficial for managing access across multiple domains.)
- Upon successful authentication, the server generates a JWT that includes header, payload, and signature.
- AuthServer send the issued token to Client. The client stores the JWT (e.g., in cookies, localStorage, or sessionStorage).
Session-based workflows follow a similar process. However, after authentication, user information is stored on the server within a session, while JWTs rely on tokens sent to the client for storage and subsequent use.
Token validation
- For subsequent API requests, the client sends the JWT in the
Authorization
header (Bearer <token>
). - The server verifies the JWT’s signature using a secret or public key and checks its claims (e.g., expiry, issuer).
- If the token is valid, the server grants the client access to the requested resources.
Session-based authentication requires the server to query a session store, which can be slow, especially if it relies on external or centralized databases. In contrast, JWT authentication is stateless, with all necessary information stored in the client token, and utilizing signature to ensure security. This eliminates the need for session management, making it faster and more scalable, especially in distributed systems.
How to revoke a JWT?
On the client side, signing out usually means clearing the local session and removing tokens (ID, access, refresh token) from storage. However, for JWT authentication, this only signs the user out locally, leaving the centralized session on the authorization server intact. As a result, users may still access other apps under the same session until token expires or is manually terminated.
Revoking a JWT (JSON Web Token) is more challenging than session-based authentication because JWTs are stateless and can’t be invalidated once issued, unless specific strategies are implemented. Common methods include:
- Short expiration times: Set a short
exp
claim (e.g., 15 minutes) for the JWT. Once expired, the user must re-authenticate. This minimizes risk if a token is compromised, as the attacker can only use it for a limited time. To maintain a seamless user experience, refresh token can be used to minimize the inconvenience of re-authentication. - Token blacklist: For critical cases (e.g., user logout, password changes), maintain a blacklist of revoked tokens. The server checks incoming tokens against this blocklist and rejects any matches. While effective, this approach requires tracking revoked tokens, which goes against the stateless nature of JWTs and can become inefficient if the list grows too large.
- Revocation endpoint: Introduce a revocation endpoint on the authorization server where tokens (e.g., refresh tokens) can be invalidated. Once a refresh token is revoked, any access tokens issued from it will no longer be renewed. This method works well in OAuth2 flows.
Advantages of JWT authentication
- Fast and more informative: The self-contained nature of JWTs makes client-side verification faster and more efficient, without the need for server interaction. They can also include custom claims (e.g., user roles or other relevant data) within the token, enabling servers to determine roles without querying a database.
- Enhanced secure: JWTs use signing and encryption techniques, making attacks more difficult.
- Cross-domain support: JWTs are perfect for Single Sign-On (SSO) and cross-domain authentication. They allow users to authenticate across multiple domains or services with the same token.
- Mobile-friendly: JWTs work great for mobile applications that need stateless authentication. Tokens can be stored on the client side and sent with each request, enhancing efficiency and ease of use.
Disadvantages of JWT authentication
-
JWT is not updated in real-time fashion
Once a JWT is signed, it cannot be revoked or updated, and it will be considered valid as long as the signature is valid and has not expired.
If the access permissions of a user change (usually degraded), the user will still have removed access to the resources until the JWT expires. Similarly, if a JWT contains role-based authorization information, the new authorization scope will not take effect until the old JWT expires. In other words, JWTs are not suitable for real-time revocation and users can set a proper expiration time to mitigate this issue.
-
Multiple-device and revocation dilemma
It is not possible to validate all issued JWTs before they expire to implement user revocation of all devices. While it is theoretically possible to revoke the signing key to make the JWT invalid, this would also invalidate all JWTs using that key, and the process of handling cache keys would make this approach impractical for simple user revocation operations.
Some identity providers might have prebuilt solutions for these JWT issues. For more info, check out "Best Practices to Enhance the JWT Authentication Experience.”
What’s the difference between JWT and Session?
Sessions and JWTs are two popular approaches for persisting authentication and authorization context in a stateless HTTP world. While both approaches have their pros and cons, they offer different benefits and drawbacks.
Sessions, provide stronger guarantees for individual request authorization and are simpler to implement securely. However, their reliance on server-side database validation introduces latency overhead, which can negatively impact the user experience for highly responsive applications.
JWTs, on the other hand, are advantageous for faster authorization and interoperability with external apps, but require more developer effort to address security complexities. For example, we can use webhooks to notify clients when the user's access is revoked, so that clients can clear the cached JWT and force the user to re-authenticate.
Since token-based authentication is more suitable for scale up with it's drawbacks still manageable, it is adopting by more and more modern applications.
Session vs. JWT: Choosing the right method
Your authentication method should match your app’s architecture and specific needs. Here’s a quick guide to help you decide:
When to use session-based authentication
Session-based authentication works best when you need real-time session control, need centralized management, or scalability isn’t a major concern. Here’s where it shines:
-
Web applications with persistent sessions
For platforms like online shopping websites, sessions are essential to track users, shopping carts, and preferences during their visit.
-
Applications requiring real-time session control
Applications such as banking or financial services benefit from server-controlled session data, ensuring robust access management and security.
-
Single-server or small-scale systems
Internal tools or small-scale apps without heavy scalability needs thrive on simple session management for ease of use and reliability.
When to use JWT authentication
JWT authentication is better suited for applications that prioritize scalability, efficiency, and distributed systems. It’s particularly useful for stateless interactions between clients and servers. Consider token-based authentication for the following:
-
Single Sign-On (SSO)
JWTs are perfect for Single Sign-On, enabling users to authenticate once and seamlessly access multiple services or applications using the same token. Share a detailed explanation about secure cloud-based applications using OAuth 2.0 and OIDC, with JWT format for both access tokens and ID tokens.
-
Mobile applications
Mobile apps often prefer JWTs for authentication since tokens can be securely stored on the device and sent with each API request. Explore the quick integration of JWT authentication for Android / iOS.
-
Microservices architectures
In microservices environments, JWTs allow each service to independently validate the token without relying on a central session store, ensuring scalability and efficiency.
-
Cross-domain authentication
JWTs excel in scenarios involving multiple domains or subdomains (e.g.,
api.example.com
,dashboard.example.com
, anddocs.example.com
). Unlike cookies, JWTs allow authentication across domains without additional dependencies. -
APIs and web services
RESTful APIs and web services commonly use JWTs for authentication because they are lightweight, portable, and eliminate the need for server-side session management. Learn more about machine-to-machine authentication for scenarios where your app needs to communicate directly with resources.
Best practices to improve JWT authentication experience
JWT authentication is a great tool, but it can come with challenges that affect user experience. Logto offers an easy and reliable solution to overcome these hurdles, making it a top choice for secure and efficient authentication.
Handling user sign-out issues with JWT
One common issue with JWT authentication is ensuring a proper user sign-out experience. Logto simplifies this process with its out-of-the-box SDK.
- By clearing tokens and local sessions on the client side and redirecting users to Logto's end session endpoint, you can easily terminate sessions on both the client application and the server.
- Additionally, Logto supports back-channel logout, enabling the AuthServer to notify all client applications sharing the same session when a user signs out.
This ensures consistent and secure session management across your ecosystem. Learn more about sign-out mechanisms and how to implement sign-out.
Handling user permission changes
Managing real-time changes to user permissions with JWT can also be tricky. Since JWTs are stateless by design, any updated permissions or roles may not take effect until the token expires. Logto offers strategies to handle this effectively:
- For decreasing permissions for this user: Use short access token expiration times or dynamically verify permissions via an API call.
- For adding new permissions for this user: Update the AuthServer to include the new permission scope and re-consent users to apply these changes.
These solutions help keep permissions up to date and ensure a safer, more responsive system. Learn more about managing real-time changes to user permissions.
Logto, which is a scalable identity access management infra, provides a complete identity solution with both cloud service and open-source version available.