Homework & Coding Practice

Homework/Practice Coding Assignment (20-min)

Extend Your API to Include User Authentication Using a Token

Steps:

  1. Step 1: Install jsonwebtoken:

    bash코드 복사npm install jsonwebtoken
  2. Step 2: Modify server.js to include authentication middleware:

    javascript코드 복사const jwt = require('jsonwebtoken');
    const SECRET_KEY = 'your_secret_key';
    
    // Middleware to authenticate token
    const authenticateToken = (req, res, next) => {
      const token = req.header('Authorization');
      if (!token) return res.status(401).send('Access Denied');
      try {
        const verified = jwt.verify(token, SECRET_KEY);
        req.user = verified;
        next();
      } catch (err) {
        res.status(400).send('Invalid Token');
      }
    };
    
    // Login route to generate token
    app.post('/login', (req, res) => {
      const username = req.body.username;
      const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '1h' });
      res.json({ token });
    });
    
    // Protect routes with the middleware
    app.get('/tasks', authenticateToken, (req, res) => {
      res.json(tasks);
    });
  3. Step 3: Run the server and test the following:

    • Use Postman to send a POST request to /login with a JSON body:

      json코드 복사{
        "username": "testuser"
      }
    • Copy the token from the response and include it in the Authorization header for subsequent /tasks requests.


Write Documentation for Your API Endpoints

  • Create a simple Markdown file (README.md) to document the API:

Last updated