0

我怀疑我在参加的课程中遇到的某些身份验证中间件代码的相对安全性。

因此,我使用邮递员向受保护的路线发送请求(请参阅下面的路线代码),并发现我能够使用为另一个用户生成的令牌检索一个用户的订单。

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

在我看来,这个中间件代码只会验证数据库中是否存在来自解码令牌的用户,但不会根据用户/令牌限制对资源的访问。

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

但是,在测试另一个受保护的路由以更新用户的个人资料信息时,我在使用错误的令牌时收到错误消息。

希望得到一些澄清

4

1 回答 1

1

jwt.verify 只会验证给定的令牌是否由服务器生成。它不关心哪个用户发送此令牌。

对于受保护的中间件,它只检查请求是否被授权。如果是这样,请求将传递给控制器​​。

至于更新路线。它可能是这样的:

// 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
}
于 2021-01-11T09:15:28.450 回答