How to use jwt in login api in node js

// Step 1: Install required npm packages
// Run the following commands in your Node.js project directory
// npm install express jsonwebtoken body-parser

// Step 2: Import required modules in your Node.js file
const express = require('express');
const jwt = require('jsonwebtoken');
const bodyParser = require('body-parser');

// Step 3: Create an instance of the Express application
const app = express();

// Step 4: Use middleware to parse incoming JSON requests
app.use(bodyParser.json());

// Step 5: Define a secret key for JWT
const secretKey = 'your-secret-key';

// Step 6: Create a login endpoint
app.post('/login', (req, res) => {
  // Step 7: Validate user credentials (replace this with your own authentication logic)
  const { username, password } = req.body;

  // Example validation (replace this with your actual authentication logic)
  if (username === 'user' && password === 'password') {
    // Step 8: Generate a JWT token
    const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });

    // Step 9: Send the token as a response
    res.json({ token });
  } else {
    // Step 10: Return unauthorized if credentials are invalid
    res.status(401).json({ message: 'Unauthorized' });
  }
});

// Step 11: Create a protected endpoint that requires a valid JWT
app.get('/protected', authenticateToken, (req, res) => {
  // Step 12: Handle protected resource logic here
  res.json({ message: 'Protected resource accessed successfully' });
});

// Step 13: Middleware function to authenticate JWT token
function authenticateToken(req, res, next) {
  const token = req.header('Authorization');

  if (!token) return res.status(401).json({ message: 'Unauthorized' });

  jwt.verify(token, secretKey, (err, user) => {
    if (err) return res.status(403).json({ message: 'Forbidden' });

    req.user = user;
    next();
  });
}

// Step 14: Start the Express server
const port = 3000;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});