---
tags: WebBasics
---
JWT vs Server-side Sessions
===
JWT and Server-side sessions are different from each other as JWT provides a means of maintaining the session on the client side, while Server-side sessions are maintained on the server.Both of these are ways to do session management.
## JWT
==JWT: JSON Web Token==
JWTs are JSON data, encoded(not encrypted) as a string, and cryptograhically signed.
There are two ways to sign JWT cryptograhically:
- Symmetric: using shared secret key -HMAC
- Asymmetric: using public/private key pair - RSA
As the JSON payload is not encrypted and everyone can decode the data so don't save any sensitive data.
There are following terms in JWT:
1. Header
2. Payload
3. Signature
4. Secret (shared or pub/private pair)
The *header* contains info about the signing algorithm,*payload* contains the claims having details like user, role, userId, expiration time, issue time, and other custom data.
```typescript=
/*
* Create JWT (pseudocode)
*/
function createToken(header:any,payload:any,secretKey:string):string {
const H=base64Encode(header);
const P=base64Encode(payload);
const S=hmac(H+"."+P,secretKey);
const JWT=`${H}.${P}.${S}`;
return JWT;
}
/*
* Verify JWT (pseudocode)
* checks if payload is tempered or not
*/
function verifyToken(JWT:any,secretKey:string):boolean {
const {header,payload,originalSignature} = JWT; //decode
const H=base64Encode(header);
const P=base64Encode(payload);
const newSign=hmac(H+"."+P,secretKey);
return newSign===originalSignature;
}
```
:pushpin: *JWT is mainly used as Authorization token*.
:::info
From the server point of view JWT is stateless as claims made by token are the part of token itself and no information needs to be verified except the verification of token and hence saving a round-trip to Database.
:::
Also JWT imposes its own set of challenges:
- Storing the token securely
- Transporting its securily
- Blacklisting of tokens
- Inability to store sensitive data in payload
- Huge Size
- Verifying the Token is CPU intensive
:::warning
It is much better to save JWT in cookie instead of local storage because local storage doesn't provide any security mechanism that cookies do.Cookies are managed by the browser and local storage is managed by Javascript. But for JWT sized more than 4KB cookie is not an option. :-1:
:::
## Server-side sessions
Server-Side sessions are stored on the server. Since all the state data is stored on the server it can be modified by the server anytime with more flexibility than JWT which once issued cannot be revoked**.
`**Logical View of Server-side sessions:**`
```typescript=
var sessionMap=new Map<string,any>(); //global cache
function createSession(claimsPayload:any){
const randomSessionId:string=new RandStr();//of big enough length,making it imposible to guess
claimsPayload.expiryTime=Date.now()+ 30mins;
sessionMap.set(randomSessionId,claimsPayload);
/* now pass this randomSessionId to the client,
* as a cookie and
* client need to pass the cookies in every request
*
* */
return randomSessionId;
}
/**
* We can make use of cryptography here as well
*/
```
:::info
Server-side sessions are completely stateful.
:::
Server-side sessions needs to be saved either in database or in-memory.Saving it in database increases complexity and saving in-memory limits horizontal-scaling (sticky-session can be used but again it has its own disadvantages,although redis can be used as a distributed cache).
:bulb:
Cookies, when used with the HttpOnly and cookie flag, are not accessible through JavaScript,only browser manages it,and are thus immune to XSS(Cross-site Scripting).
___
:information_source:
`An HTTP cookie (also called web cookie, Internet cookie, browser cookie, or simply cookie) is a small piece of data stored on the user's computer by the web browser while browsing a website. Cookies were designed to be a reliable mechanism for websites to remember stateful information`
## Conclusion
***"Stop saying that JWT sucks"***,there is a lot of negativity around JWT but if you implement the same security mechanism you would be fine.Stateless based Authentication scales very well as the application scales without bearing the cost of space required for cluster-store.