Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a suspicion about the relative security of some authentication middleware code I came across in a course im enrolled in.

So I used postman to send a request to a protected route(see route code below) and found that I was able retrieve an order for one user with a token generated for another user.

const protected = asyncHandler(async (req, res, next) => {
  let token;
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer")
  ) {
    try {
      token = req.headers.authorization.split(" ")[1];
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      req.user = await User.findById(decoded.id).select("-password");

  next();
} catch (error) {
  console.error(error);
  res.status(401);
  throw new Error("Not authorized, token failed");
}
 }
  if (!token) {
    res.status(401);
    throw new Error("Not authorized, No token found");
  }
}); 
export protected

It seems evident to me that this middleware code will only verify if a user from decoded token exists in the DB and but will not limit access to resources based on the user/token.

import {addOrderItems, getOrderbyId}  from "../controllers/orderController.js";
import { protected } from "../middleware/authMiddleware.js";
    
const router = express.Router();

router.route("/").post(protected, addOrderItems);
router.route("/:id").get(protected, getOrderbyId);
//:id is the order id

However, when testing another protected route for updating a user's profile info, I receive an error when using wrong token.

Was hoping for some clarification


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
288 views
Welcome To Ask or Share your Answers For Others

1 Answer

jwt.verify will only verify that the given token is generated by the server or not. It doesn't care which user send this token.

For your protected middleware, it just check if the request is authorized. If so, the request will pass to the controller.

As for the updating route. It probably be something like this:

// route 
router.route("/:userId", protected, updateController)

const updateController = (req, res) => {
  const user = req.user; // this is the one generated by protected middleware
  const reqUserId = req.params.userId; // this is the one send by request
  
  if (user.id !== reqUserId) {
      // if two ids are not the same, it means someone is trying
      // to update the profile with the wrong token
      res.status(401);
  }

  // update profile in database
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...