中间件保护功能未按预期工作

问题描述 投票:0回答:1

我一直在遵循指南:https://www.youtube.com/watch?v=wlxx3SCHZKk&t=10255s&ab_channel=ZinoTrustAcademy, 当我试图了解 MERN 时,但当涉及到“保护”功能的实现时,该功能将检测您是否已登录,以便使用其他登录或注册功能。它只是不起作用。

This is my protect Function: 

// authMiddleWare.js
const protect = asyncHandler(async(req,res,next)=>{
    try {
        const token = req.cookies.token;
        if (!token) {
            res.status(401)
            throw new Error("Not autorized, Please log in!")
        }
        // Verify token
    const verified = jwt.verify(token, process.env.JWT_SECRET);
    user = await FuncionarioMedico.findById(verified.id).select('-password');
    if (!user) {
        res.status(401)
        throw new Error("User not found!");
    }
    req.funcionarioMedico = user;
    next();

    } catch (error) {
        res.status(401);
        throw new Error("Not authorized, Please login!")
    }
    
})

module.exports = protect;

//这是我的路线:

router.get("/getFuncionario",protect, getFuncionario)

//这是在 Protect 之后调用的函数:这将获取我的数据:

//Get funcionario Data
const getFuncionario = asyncHandler(async (req, res) => {
    // Retrieve funcionario data
    const funcionario = await FuncionarioMedico.findById(req.funcionario._id);

    if (funcionario) {
        // Destructure funcionario properties
        const {_id, name, email, image, phone} = funcionario;
        res.status(200).json({
            _id,
            name,
            email,
            image,
            phone
        });
    } else {
        res.status(400);
        throw new Error("Invalid Username or Password!");
    }
});

我不确定问题出在哪里,因为我严格遵循指南,我在使用 API CRUD 方面还很陌生。也就是说,我不知道自己在做什么。

这个项目有学术目的,为了测试它必须使用迅雷客户端,所以用失眠来测试是不可能的。

登录并注册后,无论是否存在令牌,它都会向我抛出错误:“未授权,请登录!”,就像没有令牌一样。我不确定我是否做错了什么,或者只是一个测试错误,因为正如我所说,我正在使用 Thunder 客户端。

完整代码(以防万一):https://github.com/yzkael/homeWorkMERN

除了当前的错误之外,我将不胜感激任何反馈,因为我真的很深入研究 MERN!

node.js express jwt crud mern
1个回答
0
投票

您应该从标头中的

Bearer Token
字段获取令牌。这是可以提供帮助的代码。

exports.protect = catchAsyncError(async (req, res, next) => {
  let token; // get token sent by the user
  if (
    req.headers.authorization &&
    req.headers.authorization.startsWith("Bearer") // check if the token exists
  ) {
    token = req.headers.authorization.split(" ")[1];
  } else {
    return next(
      new AppError(404, `You're not logged in. Please login to access.`)
    ); // token is invalid or token is not present
  }

  const { id } = jwt.verify(token, process.env.JWT_SECRET_KEY); // decode and get id

  if (!id) { 
    return next(
      new AppError(404, `You're not authorized to access the resource`)
    );
  }

  const user = await AllUsers.findById(id).select("+otp password");

  if (!user) {
    return next(
      new AppError(404, `No user found.`)
    );
  }

  req.user = user;
  next();
});
© www.soinside.com 2019 - 2024. All rights reserved.