What Is the Difference Between Sessions and JSON Web Tokens (JWT) Authentication?
Sessions and JSON web tokens (JWT) are the two most common methods of authentication. For Node.js applications. If you are building an ExpressJS login form for example, you will probably choose one of these methods to authenticate users, but may not be sure which one is right for your application.
In this tutorial, we’ll learn:
- What is session authentication?
- What are JWTs and how are they used for authentication?
- How are sessions and JWTs different?
- How to choose an authentication method for your project
By the end of this tutorial, you will understand and be able to compare sessions and JWT. And to determine which one you should use for your Node/Express project. This tutorial focuses on username/password type authentication, but the concepts learned apply to other forms as well.
This tutorial is part 5 of 7 tutorials that walk through using Express.js for user authentication.
Goal
Understand session and JWT authentication to choose the best method for your project.
Prerequisites
What is session authentication?
A session is a period of interaction between a user and a website. When a user successfully logs into a site that uses session-based authentication, the current session gets assigned an identification number. This session ID gets stored in a cookie. A cookie is data sent from a website and stored on the client side. Only small amounts of data can fit in a cookie.
Sessions use the session ID to access data stored on the server, making it stateful. Common types of session storage include:
- Memory Cache (Redis)
- NoSQL Database (MongoDB)
- SQL Database (MySQL, PostgreSQL)
- Server File (JSON, TXT)
- Server Memory
What are JSON Web Tokens (JWT)?
JWT is a stateless type of authentication. It does not use external storage. Instead, data is stored directly in the token. When a user successfully logs in, the server creates and signs a JSON web token. The server sends the token back to the client. The token may get stored in a cookie. All the needed data gets stored in the token, so the server is no longer involved.
There are three main parts of a JWT:
- Header: The header includes the signing algorithm used and the type of token. The token type is “JWT”.
- Payload: The payload is the user data that the token stores. Common data include the issuer of the token, the subject of the token, the time the token is issued, and the time it will expire.
- Signature: The signature validates the sender, ensuring the token is trustworthy.
Here is an example JWT:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTYiLCJuYW1lIjoiQ2FuZHkgQ2FuZSIsImV4cCI6MTYxNjI4OTA3NCwiaWF0IjoxNjE2MjgzMDcyfQ.4a5-NQSCJCBCOGMNWfRD93XymholkOwOxU-wFNTQ-v4
Notice there are 3 parts, separated by dots (.). The first part is the header, the second is the payload, and the third is the signature.
Next, let’s look at the data in the JWT above.
Header:
- Algorithm: HS256
- Type: JWT
Payload:
- Subject: 123456
- Name: Candy Cane
- Expires: 1616289074 (March 20, 2021 21:11:14 EST)
- Issue Date: 1616289074 (March 20, 2021 19:31:12 EST)
Signature:
- Secret: Yey^]YmhDs/k$h}6*]^y]5XaF4*
You can go to jwt.io to decode the token.
Because JSON web tokens get stored on the client side, they must not contain sensitive data. It is possible to view and decode the tokens, making them susceptible to malicious attacks.
What is the difference between sessions and JWT?
The main difference between sessions and JWT is how they authorize access to data. Both methods usually use a standard POST request to authenticate username and password. Once the user is verified, they will have access to specific data. The JWT token contains all the information needed to grant them access, without doing a server call. Sessions store the session ID on the client side, but still have to talk to the server to grant authorization.
What are the advantages of JWT?
- Local authorization: Because JWT is stateless, no database queries or server calls are necessary to grant users access to data. All the authorization data gets stored in the token. All else being equal, local access means faster load times.
- Implementation across multiple servers and domains: A JWT functions like a skeleton key. It can give the user access to any data that fits the key, easily granting access across multiple domains using servers. A JWT can travel via HTTP request header.
- No cookies required: You can store tokens in a cookie, but you do not have to, which provides extra flexibility to the developer.
- Less server resource allocation: Since JWT does not require authorization data to get stored on a server, fewer server resources get used. If an application is extensive, with many users, this could make a big difference.
What are the disadvantages of JWT?
- Signature algorithms take time: It is possible to use JWT without a signature, but this is not advisable. The more complex the signature algorithm, the longer it will take to decode. Slower load times mean higher security. Stateless time gains can be outweighed by the signature algorithm.
- Revoking user access: When a token gets created, it is assigned an expiration date. Once the token expires, the user will get logged out and will no longer have the authorization to access data. On the other hand, in cases of tampering, changing a user’s password is not enough to kick out a user with a valid token. There are methods to disallow the unlawful user, but it takes extra steps.
- Data is on the client side: This is both an advantage, as explained above, and a disadvantage. Because the information is on the client side, it is accessible to users, malicious and benign alike. Although you may encrypt the token’s payload, storing sensitive data in a token is still like playing with fire.
- JWT store a lot of data: Compared to a session ID, tokens contain much more data that the client must store and transmit. If you store the token in a cookie, you must be careful not to exceed the recommended data size. If you store the token in local storage, you open your application up to additional security threats.
What are the advantages of sessions?
- Accessing sensitive data: Sensitive data can get stored in a secure database and accessed via the session ID.
- Easy to delete: When a user’s login details are compromised, you can delete the session in the database and revoke access.
- Longevity: Sessions have a long history of success. You can easily find libraries, code snippets, and tutorials that use sessions. You are also likely to run into organizational code that already has sessions implemented.
- Many applications are not stateless: Aside from authentication, many applications already rely on database calls and server communication to load page data.
What are the disadvantages of sessions?
- Difficult to implement across domains: Session IDs get stored in cookies, and most cookies only work on one single domain. Third-party cookies can work on multiple domains, but they are challenging to implement and commonly blocked by web browsers.
- Server resource allocation: If your site has a lot of users, you will be storing a lot of session data on the server.
- More server calls: Your application will have to communicate with the server to authorize access to data.
How do I decide which method is right for my project?
Like most web development methods, a large portion of the decision is based on personal preference, and there is never a one-size-fits-all solution. It is essential to weigh the pros and cons and analyze what best fits with your programming style and your application’s architecture. If coded correctly, the majority of applications will work well using either method.
Recap
The 2 most popular authentication methods are JSON web tokens (JWT) and Sessions. JWT are stateless, storing all authorization data in a token on the client-side. They are easier to implement if your application uses multiple domains and back-ends. Sessions are a stateful method that work by assigning the user a session ID that gets stored in a client-side cookie. Applications use the session ID to access user information that is stored on a server. Although sessions have a long history of success, they require a larger allocation of server resources.
To decide which method is best for your application you must weigh all the pros and cons relative to your application’s needs and your style of programming.
Keep going with the next tutorial in this set: Set Up ExpressJS Session Authentication for Node Applications.
Further your understanding
- Which method would you use for a blog site?
- Which method would you use for a banking application?
- Can you think of an application you have built or used that is completely stateless?
Additional resources
- Express-sessions on npm (npmjs.com)
- Express-jwt on npm (npmjs.com)
- Set Up Express Session Authentication (HeyNode.com)