Lab11 - Authentication and Authorization
Lab11 - Authentication and Authorization
Objective:
To implement secure user authentication using JSON Web Tokens (JWT) in an Express.js
app. The user data will be stored in MongoDB using Mongoose. Students will learn about
password hashing, token generation, and protecting routes.
Activity Outcomes:
header.payload.signature
Example:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJ1c2VySWQiOiIxMjM0NTYiLCJyb2xlIjoiYWRtaW4ifQ.
sflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
1. Header:
Specifies the type of token and the algorithm used to sign it.
{
"alg": "HS256",
"typ": "JWT"
}
2. Payload:
Contains the claims — information like user ID, email, role, etc.
{
"userId": "123456",
"role": "admin",
"iat": 1715589993,
"exp": 1715593593
}
3. Signature:
Used to verify the token’s authenticity and integrity.
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
Pros of JWT:
Stateless: No need to store session data on the server.
Scalable: Great for microservices and APIs.
Portable: Easily passed around via headers, cookies, or URLs.
npm init -y
npm install express mongoose bcrypt jsonwebtoken dotenv
models/User.js
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
routes/auth.js
// Register Route
router.post('/register', async (req, res) => {
try {
const { username, password } = req.body;
const exists = await User.findOne({ username });
if (exists) return res.status(400).json({ message: 'User already exists' });
module.exports = router;
middleware/auth.js
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
res.status(403).json({ message: 'Invalid token' });
}
};
module.exports = auth;
routes/protected.js
module.exports = router;
server.js
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const authRoutes = require('./routes/auth');
const protectedRoutes = require('./routes/protected');
mongoose.connect(process.env.MONGO_URI, () => {
console.log('Connected to MongoDB');
});
app.use('/auth', authRoutes);
app.use('/api', protectedRoutes);
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
MONGO_URI=mongodb://localhost:27017/jwt-lab
JWT_SECRET=supersecretkey