Jwt令牌认证与Node.js无效的令牌

时间:2020-08-02 19:48:24

标签: node.js jwt token

我正在使用通过jwt(jsonwebtoken)进行令牌身份验证的NodeJ。

我正在尝试将身份验证添加到端点,以验证提供的令牌是否正确, 接下来是我的方法:

async function create(req, res) {
  try {
    const token = req.headers["access-token"];
    console.log("token:" + token);
    console.log("decodedToken:", req.decoded);
    return res.status(200).send(req.body.comments);
  } catch (error) {}
}

 async function verifyToken(req, res, next) {
      const tokenHeader = req.headers["access-token"];
      const token = tokenHeader.split(" ")[1];
      console.log("tokenVerify:", tokenHeader.split(" ")[1]);
      console.log("tokenn:", token);

  if (token) {
    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {
      if (err) {
        return res.json({ mensaje: "Invalid Token." });
      } else {
        req.decoded = decoded;
        next();
      }
    });
  } else {
    res.send({
      mensaje: "No provided token.",
    });
  }
}

module.exports = {
  create,
  verifyToken,
};

这是我的路线代码:

app.post("/comment/", verifyToken, commentsController.create);

但是我总是收到一条Invalid Token.消息。

这是当用户尝试登录应用程序时生成令牌的方式:

function generateAccessToken(user) {
  return jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, { expiresIn: 1440 });
}

我正在使用以下格式的令牌通过令牌传递

承载eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9....后一个字符。

1 个答案:

答案 0 :(得分:0)

问题似乎在于您没有正确地从标头中剥离令牌。这就是你所拥有的:

async function verifyToken(req, res, next) {
  const token = req.headers["access-token"];
  console.log("tokenVerify:", token.split(" ")[1]);

  if (token) {
    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {

请注意,您要删除console.log中的令牌,而不是实际代码中的令牌。所以,这是您需要的:

async function verifyToken(req, res, next) {
  const tokenHeader = req.headers["access-token"];
  const token = tokenHeader.split(" ")[1]);
  console.log("tokenVerify:", token);

  if (token) {
    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => {