Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

node.js - Authorization middleware JWT confusion

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


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

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...