Sessions Strategies (JWTs, Database Session)
Mohanad Alrwaihy
April 16, 2023
124
2
When a user Sign In to a website user session should be saved in order to confirm future requests from the user and to persist user session in the website for a limited amount of time.
6 min read
When a user Sign In to a website user session should be saved in order to confirm future requests from the user and to persist the user session in the website for a limited amount of time.
JSON Web Tokens (JWTs)
In JWTs, the data is stored as a JSON object on the Client Side as soon as it's issued by the server and it includes three parts Header, Payload, and Signature.
These parts are separated by a dot:
MARKDOWN
xxxxx.yyyyy.zzzzz
JWT Header
- Token Type.
- Signing Algorithm. - JWT Signing Algorithm Overview
JWT Payload
JSON
{
"alt": "HS256",
"typ": "JWT"
}
The payload contains information about the Claims (Typically user data) and additional information. There are three types of claims:
- Registered - Recommended predefined claims.
- iss (issuer)
- exp (expiration time)
- sub (subject)
- aud (audience)
- Public - Defined those who will be using JWTs.
- Private - Custom Claims created to share information between parties.
JSON
{
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239022
}
JWT Signature
The signature is created by taking the encoded header, the encoded payload, and a secret, and signing that.
The signature is used to verify that the message was not changed and to verify the sender of the JWT.
Signature with HMAC SHA256 Algorithm:
JSON
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
JWT Advantages
- The database is not required to store sessions which leads to faster and cheaper implementation and scale.
- JWTs are secure using cryptographic encryption (JWE) to store and include information inside the JWT session token.
- Store additional information for clients (User Specific Information for example.) as JWT is stored in a Server Readable Only cookie so the data can not be accessible from a third-party JavaScritp running on the Website.
JWT Disadvantages
- JWTs can't be easily expired because they required a Server Side blocklist of invalid tokens and checking every token every time a new token is created. (Shorter Session Expiry times are used to simplify the problem.)
- Limited data to around 4KB per cookie (Can vary between browsers but to support all browsers it must not exceed 4KB).
- Data stored in encrypted JWTs may be compromised even if its configured properly the decryption of the token should not be assumed to be impossible as at any time in the future a defect or advance in technology may be introduced.
Database Session (Session Tokens)
When using Session Tokens the user's authentication state is stored in a database as a record with this information:
- Primary identifier for the session (UUID) or any kind of unique identifier.
- User Identifier (User ID) in the database to verify and refer the session is for this user.
- Session Start Time.
- Session Expiry Time.
- Other Information can be added as well.
Session Token Advantages
- More Control - A session saved in a database can have more options for the session and additional information with more space.
- Bandwidth Consumption - Uses very little bandwidth because it only sends the Session ID instead of JWTs where the token has the payload which might be large or increase with time.
- Data Visibility (Secure) - Since Session ID is the only available data in the Cookie there is no chance of getting any information leaked or in the case of JWT where anyone can read it or have an idea of how data is structured.
The right Choice JWTs or Session Tokens 🤔
There are a lot of factors to determine which one is the best for your application but first, let's look at the differences between these two method:
- JWTs are faster - Since it does not require a Database to store session information.
- Session Token is more Secure - Since the session is guaranteed to be for a certain user that makes it easier to implement and authorize user requests.
To determine the best choice we can look at these questions and answer them accordingly to find out the best choice:
1. How Sensitive is the Information?
For Applications like a bank or Government Agency which have extremally sensitive information. Session Token might be the best approach to ensure every single call is authorized.
2. What is the scalability of your application?
Scaling is much easier with JWTs because no repeated calls to the server are needed to re-authenticate the session.
3. Modern features used in your application?
Modern features in the Web like serverless computing, cross-domain functionality, and mobile-specific or Single-page application (SPA) using JWTs are preferred.
4. How important are Performance and uptime?
Does your application need to provide a faster experience to users?
- Live services - JWTs may be the best option.
In other applications where latency is not a problem for the end user then Session Token can be an option.
Combining JWTs and Session Tokens 😮
As most will always suggest using one of these Session Management tools there have been some implementations using Both by returning a Session Token and JWT when a user starts a session.
- Session Token - Static Value for the lifetime of the session (Stored in a database).
- JWT - Short lives expiry time.
The idea is the JWT can be passed to the session API to retrieve a fresh JWT when it's expired and ensure that the Session Token is still active before passing back a new JWT.
The advantage of using this method is that instead of authorizing the user session for every request with the Session Token which takes time. the JWT will be used for authorization which greatly reduces the performance overhead while also protecting you and your end users.
This method leverages both Session Token Security 🔒 with JWT Performance ⚡.
NextAuth to use JWTs or Session Token
I have created a Post showing how to use JWTs or Session Token strategies with NextAuth. Click Here