Week -11
Aim:For the above application create authorized end points using JWT (JSON Web Token)
Step 1:First, install the jsonwebtoken package:
npm install jsonwebtoken
Step 2: update the server.js file:
Source code:
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const app = express();
const PORT = 3000;
const JWT_SECRET = 'your_secret_key'; // Replace with your own secret key
// Dummy user data
const users = [
{ id: 1, username: 'admin', password: 'password' }
];
// Dummy student data
let students = [
{ id: 1, name: 'John Doe', age: 20 },
{ id: 2, name: 'Jane Smith', age: 22 }
];
app.use(bodyParser.json());
// Middleware to authenticate JWT token
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
// Login endpoint to generate JWT token
app.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username && u.password === password);
if (!user) return res.sendStatus(401);
const accessToken = jwt.sign({ username: user.username, id: user.id }, JWT_SECRET);
res.json({ accessToken });
});
// Authorized endpoints
app.get('/students', authenticateToken, (req, res) => {
res.json(students);
});
app.post('/students', authenticateToken, (req, res) => {
// Same as before
});
app.put('/students/:id', authenticateToken, (req, res) => {
// Same as before
});
app.delete('/students/:id', authenticateToken, (req, res) => {
// Same as before
});
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
With this setup, the /login endpoint accepts a username and password and returns a JWT token. You can
then use this token in the Authorization header (Bearer <token>) to access the authorized endpoints
(/students). The authenticateToken middleware verifies the JWT token before allowing access to these
endpoints.
Make sure to replace 'your_secret_key' with a strong, unique secret key in a real-world application.
THE STEPS TO EXECUTE THE PROVIDED PROGRAM:
1. Setup the Environment:
o Make sure you have Node.js installed on your system. If not, download and install
it from the official Node.js website.
o Create a new directory for your project.
o Open a terminal or command prompt and navigate to the project directory.
2. Initialize the Project:
o Run npm init -y in the terminal to initialize a new Node.js project with default
settings.
3. Install Dependencies:
o Run npm install express body-parser jsonwebtoken to install Express,
Body-parser, and Jsonwebtoken packages.
Step 1:First, install the jsonwebtoken package:
4. Create the Server File:
o Create a file named server.js in your project directory.
5. Copy and Paste Code:
o Copy the provided code snippet and paste it into the server.js file.
6. Replace the Secret Key:
o Replace 'your_secret_key' with a strong and unique secret key of your choice.
It's important to keep this key secure.
7. Save the File:
o Save the server.js file.
8. Run the Server:
o In the terminal, run node server.js to start the Express server.
9. Test the Endpoints:
o Use a tool like Postman to test the endpoints.
o Send a POST request to http://localhost:3000/login with a JSON body
containing username and password to obtain a JWT token.
o Use the obtained token to make requests to the authorized endpoints (/students).
For example, you can send a GET request to
http://localhost:3000/students with the token in the Authorization header
(Bearer <token>).
10. Verify the Output:
o Verify that you receive the expected responses from the endpoints.