Comparing token-based authentication and session-based authentication
Tags: webdev, security, programming, opensource
Published: 2024-05-14 03:47:53

This blog post introduces the basic concepts of both token-based authentication and session-based authentication, with their pros and cons. This could help readers to choose the proper authentication scheme for their application.

Generally speaking, the first step in using an application is signing in or 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.

Applications often provide full functionality through many APIs. In subsequent API calls, what happens if the user is unable to provide valid accesses?

HTTP is stateless, which means each request is independent and does not contain any context information related to the previous request. However, requiring the user to re-authenticate for every request is definitely not a good user experience.

Sessions and JSON Web Tokens (JWTs) are two of the most common methods used to maintain authentication state across multiple calls. Both methods have their pros and cons, and the choice of which method to use depends on the specific needs of your application.

# Session-based authentication

In session-based authentication, the server is responsible for creating and maintaining the user's authentication state and providing a way to reference that record in each subsequent request.

The process begins when the user authenticates and provides some credentials. If the credentials are valid, the server creates a persistent record representing that session, containing information such as a random string, user identifier, session start time, session expiration time, and so on. This record is stored in the database and returned to the user’s agent (for example, browser) as a cookie.

Each subsequent calls sends an HTTP request from the browser containing the session cookie. The server can use this cookie to look up the session record, verify its validity, and make authorization decisions based on the user's identity.

## 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
At scale, session authentication may introduce latency because it requires database interaction, which could impact application performance.

#### High resource consumption
Because of the need to store and retrieve large numbers of session records, session authentication may consume more resources.

# JWT authentication

JSON Web Tokens (JWTs) use a different method to achieve authentication and authorization.

The process begins with the user providing authentication credentials, and the server uses those credentials to verify the user's identity. Unlike session authentication, however, JWTs use a JSON object to contain all relevant information and employ signatures or encryption to verify their integrity and validity.

A JWT consists of three parts: a **header**, **payload**, and **signature**.

The **header** contains algorithm information about signing and decoding.

The **payload** contains core claims, such as the user's identity, authorization permissions, and expiration time.

The **signature** uses a key to sign the payload, allowing verification of whether the signature has been tampered with.

## Advantages of JWTs

#### Fast and efficient
The self-contained nature of JWTs makes client-side verification faster and more efficient, without the need for server interaction.
#### Secure
JWTs use signing and encryption techniques, making attacks more difficult.

## Disadvantages of JWTs

#### 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.
# Sessions or JWTs?
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.
# Choosing a proper method
Which method you choose depends on the specific needs of your application.

If your application handles sensitive data or requires rapid revocation, session-based authentication may be the better choice.

If your application needs fast, efficient authorization or requires more interaction between the client and server, token-based authentication may be more suitable.

Logto, which is a scalable identity access management infra, provides a complete identity solution with both cloud service and open-source version available.

{% cta https://logto.io/?ref=dev %} Try Logto Cloud for free {% endcta %}