我怀疑我在参加的课程中遇到的某些身份验证中间件代码的相对安全性。
因此,我使用邮递员向受保护的路线发送请求(请参阅下面的路线代码),并发现我能够使用为另一个用户生成的令牌检索一个用户的订单。
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
但是,在测试另一个受保护的路由以更新用户的个人资料信息时,我在使用错误的令牌时收到错误消息。
希望得到一些澄清