JWTs o Cookies de sesion El Dilema de la Autenticación en Entornos Web

JWT or Session Cookies: The Dilemma of Authentication in Web Environments

One of the most critical aspects of any application or web system is often authentication.

Authentication and Authorization

autenticación y autorización

Authentication is the process by which a system verifies a user’s or device’s identity. In addition to authentication, there is the authorization process. The authorization process validates whether such a user or device has permission to access a specific resource.

When working on the authentication system, the main challenge we must deal with is that HTTP is stateless. Each request is independent and does not contain any context about previous requests. So, how do we handle requests that are made after passing authorization?

Session Cookies and JWT: Two Authentication Options

This is where Session Cookies and JWT (Json Web Token) come into play. We must choose how to manage authenticated users for an optimal web system and user experience. And consider the pros and cons of choosing one option over the other.

Session-Based Authentication

Session-based authentication occurs when the user enters their credentials, and the server generates a persistent record representing this browsing session.

This record usually includes a primary identifier, one for the user. It also includes the login start date and time, IP address, and client UserAgent. This information is stored in the database. The session identifier is returned in the HTTP response, and stored as a cookie in the user’s browser. From here on, each request will include the session identifier, allowing the server to verify its validity and decide on the data or information to return.

Advantages and Disadvantages of Session-Based Authentication

It’s important to know the advantages and disadvantages of session-based authentication to make the right decision based on our needs.

ventajas y desventajas2

Let’s start with the advantages:

  • Simplicidad: Las Cookies de Sesión son fáciles de implementar y usar, lo que las hace adecuadas para aplicaciones con una estructura simple. 
  • Session Persistence: Cookies allow users to keep their session open even after closing the browser, providing convenience and improving the user experience.
  • Escalabilidad: Para aplicaciones con alta concurrencia, el uso de Cookies de Sesión puede aliviar la carga del servidor al almacenar información de autenticación en el cliente, lo que permite gestionar un mayor número de usuarios. 
  • Session Control: Cookies enable system administrators to revoke or manipulate user sessions more easily, improving security.

However, session-based authentication also has its drawbacks to consider before making decisions.

  • Security Risk: Session Cookies can be vulnerable to identity theft attacks if not managed correctly. Stolen cookies could allow unauthorized access to the user’s account.
  • Privacy Issues: Improper use or storage of sensitive data in Cookies can raise concerns about the privacy of personal user information.
  • Browser Compatibility: Cookies may work inconsistently across different browsers, leading to usability issues.
  • Session Management Complexity: Session management with Cookies can become more complex as the application size grows, requiring additional planning and organization.

JWT (Json Web Token) Based Authentication

Another option available for performing and maintaining authentication in web environments is to use JWT, or Json Web Token.

This flow also begins when the user provides some credentials, and the server uses them to authenticate the request. However, in contrast to session-based authentication (where we store the session state and retrieve it in each request), JWT differs significantly. All this context is self-contained in the chain sent back to the client. Information can be retrieved from it without the need to query the database; the necessary information is in the token, and it can be read if permissions allow.

In simpler terms, JWTs are standardized JSON objects generated and signed during the authentication process, guaranteeing their trustworthiness.

Components of a JWT

If we analyze a JWT, we can see that it consists of three parts: the header, the payload, and the signature. When servers receive JWTs, they can verify that they have not been manipulated since the signature of the JWT contains the original header and payload data.

The payload part contains three elements related to the user, permissions, and expiration. The user is the identity for which the JWT was issued. Permissions are associated with it, and expiration is the token’s validity period.

Information about the algorithm used to sign or encrypt the token is in the header. Both the header and payload are base64-encoded. The signature part is created in this way: the header and payload are combined, and then a hash is applied to that combination with a secret key. This allows detecting if someone has manipulated the notifications after signing the JWT.

In distributed systems, this operation is performed with asymmetric signatures. The server issuing the JWT uses a private key to encrypt the content. Then, the audience can use the corresponding public key to verify that the current payload is the same as the one the issuer signed.

Advantages and Disadvantages of JWT-Based Authentication

ventajas y desventajas

Now, let’s detail some advantages and disadvantages of using JWT:

Starting with the advantages:

  • Seguridad: Los tokens JWT pueden ofrecer un nivel sólido de seguridad, ya que están firmados digitalmente y pueden cifrarse, protegiendo la integridad de la información de autenticación. 
  • State Independence: JWTs are independent of the server’s state, meaning they do not require the server to maintain information about user sessions. This facilitates scalability.
  • Portabilidad: Los tokens JWT pueden ser utilizados en diferentes sistemas y servicios, lo que los hace ideales para aplicaciones distribuidas y microservicios. 
  • Customized Information: You can include custom data in the JWT, allowing easy customization of user sessions and roles.
  • Rendimiento: Al eliminar la necesidad de almacenar información de sesión en el servidor, los tokens JWT pueden mejorar el rendimiento de la aplicación, ya que reducen la carga en el servidor. 

On the other hand, it’s also advisable to know the disadvantages of JWT-based authentication:

  • Revocation Impossibility: Once issued, a JWT is valid until it expires. They cannot be efficiently revoked, which can be a problem if a token is stolen or compromised.
  • Complejidad: La implementación de JWT puede ser más compleja en comparación con las Cookies, especialmente en aplicaciones de gran escala. Requiere una gestión más detallada de tokens y claves. 
  • Privacy Concerns: Since JWTs contain user information, there is a potential privacy risk if tokens fall into the wrong hands.

Final Considerations and Security

As evident, each method has its pros and cons. Hence, understanding the system’s requirements to be developed is crucial. This way, we can decide on one option or another, or a combination of both if the system demands it. We acknowledge that each application possesses its uniqueness, and it’s essential to assess the balance between security and latency.

Are both methods 100% secure?

We can consider both authentication methods secure, as long as we ensure the overall security of our system. Not everything depends solely on authentication. We must take care of JWT generation and storage (if using this option). Above all, we must be careful about where we store them.

It is common to store JWTs in the browser’s LocalStorage. In this case, the best practice would be to store them in a cookie with the HttpOnly option. This prevents the token from being accessible to the user or an intruder. In cookie-based authentication, it’s also important to use the HttpOnly option. Additionally, we must be cautious about our API methods and the use of HTTP verbs.

It’s also crucial to review our website to prevent Cross-Site Request Forgery (CSRF) attacks.

Conclusions

The choice between Session Cookies and JWT for authentication in web environments is not trivial. Each has its advantages and disadvantages, and the choice should be based on the specific requirements of your application.

Considering factors such as simplicity, security, scalability, and privacy is important when making a decision. In some cases, a combination of both methods may be the optimal solution.

Ultimately, the security of your system depends on how you implement and manage authentication, regardless of the option you choose. Balancing security and latency is essential to provide the best experience for your users and protect their data.

Thank you for taking the time to read about the authentication dilemma in web environments. We hope this information helps you make informed decisions and design secure and efficient web systems. If you have questions, need advice, or want to discuss how we can collaborate, feel free to contact us.

Agustín Plaza Alcántara – Lead Developer at Itequia