Adding Authentication to Existing Routes

To protect a route, add the authenticateToken middleware.

The PATCH route below demonstrates two levels of security:

  1. Authentication: The authenticateToken middleware ensures only logged-in users can access these routes.
  2. Authorisation: We compare req.user.id (the authenticated user’s ID from the JWT token) with req.params.id (the user ID in the URL) to ensure users can only modify their own accounts. This is why we added the user property to the request.

In routes/users.ts:

// other imports
import { authenticateToken } from "../middleware/auth-validation";

router.patch(
  "/:id",
  authenticateToken,
  validateUserId,
  validateRequiredUserData,
  async (req, res) => {
    const userId = Number(req.params.id);
    const { username, email } = req.body;

    // Check if user is trying to update their own account
    if (req.user!.id !== userId) {
      return res.status(403).json({
        error: "Users can only update their own account",
      });
    }

    // ... rest of existing PATCH code
  }
);

What We’re Doing Here

  • Protect modify operations: Add authenticateToken middleware to the PUT routes.
  • Add authorisation checks: Compare req.user.id (from JWT) with req.params.id (target user).
  • Enforce user-only access: Users can only modify their own accounts, not others.
  • Return 403 errors: Block unauthorised attempts with clear error messages.

Testing the Protected PATCH Route

With the middleware and ID check added, call the endpoint without an Authorization header.

PATCH /user/<id>
{ "email": "...", "username": "..." }

You should receive the error message:

{
  "error": "Access token required"
}

Now, log in with an email and password, then add the token you receive to the header. Ensure the ID in the route matches the user you logged in as.

Headers: Authorization Bearer token-here

The PATCH request should be a success.

Now change the ID in the route:

PATCH /user/<different-id>

Because you’re trying to modify a different user’s account than the one you’re authenticated as, you should receive an error:

{
  "error": "Users can only update their own account"
}


Repo link

Tags: