Session Management
● Manages user state across multiple requests.
● Stores session ID in cookies, URL, or browser storage.
● Session data (user login, cart, etc.) = Session State.
● Sessions can timeout for security.
● Useful for tracking users and handling multiple requests.
Node.js Session Libraries
1. express-session – Simple server-side session
management.
2. connect-redis – Stores sessions in Redis (for
scalability).
3. cookie-session – Stores session data in cookies.
● Installation
npm install express express-session
● File session Management.js:
const express = require('express');
const session = require('express-session');
const app = express();
app.use(session({
secret: '7332',
resave: false,
saveUninitialized: true,
cookie: { secure: false }
}));
app.get('/', (req, res) => {
req.session.visitCount = (req.session.visitCount
|| 0) + 1;
res.send(`Visits: ${req.session.visitCount}`);
});
app.listen(3005, () => {
console.log('Running on http://localhost:3005');
});
Running the application (Session 1):
URL: http://localhost:3005/
Authorization using JWT
JWT stands for ‘JSON Web Tokens’ which is a method to
perform authentications and authorizations in applications. It is a
compact representation of claims to be transferred.
There are three parts to a JWT which are all separated by
dots (.):
1. Header: Metadata of the token, specifying signing algorithms
such as HMAC or RSA.
2. Payload: Holds the claims about the user and additional data
such as User ID, roles and auth expiration times.
3. Signature: Ensures that the token has not been tampered with.
The header and payload are put together and digitally signed
using a secret key.
Authorization using JWT
Structure of JWT: <header>.<payload>.<signature> where
header, payload and signature are alphanumeric strings.
Process of JWT Authorization:
1. User Login: User sends authorization credentials to the server
and receives a JWT from the server if the credentials are
accepted.
2. Token Storage: Client application stores the JWT using local
storage or cookies.
3. Requesting Protected Resources: While requesting for
protected resources, the client includes the JWT in the auth
header: Authorization: Bearer <token>
4. Token Verification: After receiving the request, the server
verifies the Signature using the secret key.
5. Access Control: On successful validation. The request is
Authorization using JWT
Structure of JWT: <header>.<payload>.<signature> where
header, payload and signature are alphanumeric strings.
Process of JWT Authorization:
1. User Login: User sends authorization credentials to the server
and receives a JWT from the server if the credentials are
accepted.
2. Token Storage: Client application stores the JWT using local
storage or cookies.
3. Requesting Protected Resources: While requesting for
protected resources, the client includes the JWT in the auth
header: Authorization: Bearer <token>
4. Token Verification: After receiving the request, the server
verifies the Signature using the secret key.
5. Access Control: On successful validation. The request is
Develop a codebase
with JWT
We will implement JWT authorization in Node.js using jsonwebtoken
library.
To begin we have to install the dependencies of jsonwebtoken.
npm install express jsonwebtoken body-parser
Step 1: Setup Environment
● Create a file: jwtAuthorization.js
● Run in terminal:
npm install express jsonwebtoken body-parser
📦 Step 2: Import Required Packages
const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');
⚙️Step 3: Initialize App
const app = express();
const PORT = process.env.PORT || 3007;
const SECRET_KEY = 'jwt.example.chapter17';
🧠 Step 4: Use Middleware
● Enables JSON parsing in requests:
app.use(bodyParser.json());
👤 Step 5: Mock User Data
const users = [{ id: 1, username: 'testUser1', password: 'password' }];
🔑 Step 6: Create Login Route
● Verifies credentials
● Signs a JWT if correct
app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username && u.password ===
password);
if (user) {
const token = jwt.sign({ id: user.id }, SECRET_KEY, { expiresIn: '1h' });
return res.json({ token });
}
res.status(401).send('Invalid credentials');
});
Test this POST route using Postman
🧪 Step 7: Create Middleware to Verify JWT
const authenticateJWT = (req, res, next) => {
const token = req.headers['authorization']?.split(' ')[1];
if (token) {
jwt.verify(token, SECRET_KEY, (err, user) => {
if (err) return res.sendStatus(403); // Forbidden
req.user = user;
next();
});
} else {
res.sendStatus(401); // Unauthorized
🔐 Step 8: Create a Protected Route
● Only accessible with valid token
app.get('/protected', authenticateJWT, (req, res) => {
res.send('This is a protected route. Your authorization was
successful');
});
🚀 Step 9: Start the Server
app.listen(PORT, () => {
console.log(`Auth server started on http://localhost:$
{PORT}`);
});