最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - JWT token invalid, but why - Stack Overflow

programmeradmin0浏览0评论

I'm doing one of my first exercises on authorization, but I can't understand what I'm doing wrong with this one. I'm trying to validate the JWT token, but it gives me back that it's invalid

I get the token with httpie:

http POST :4000/auth/login [email protected] password=test

And then I try validating with httpie:

http GET :4000/images authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImlhdCI6MTY0ODgyMDI3MCwiZXhwIjoxNjQ4ODI3NDcwfQ.AhArOvQTaJ7ohbPiyGiGTK5pFMWqjbZ5Kj9q2hXEhXU"

Which gives me: Invalid JWT token

This is my router/images.js

const { Router } = require("express");
const Image = require("../models").image;
const router = new Router();
const toData = require("../auth/jwt");

router.get("/images", async (req, res) => {
  const auth =
    req.headers.authorization && req.headers.authorization.split(" ");
  if (auth && auth[0] === "Bearer" && auth[1]) {
    try {
      const data = toData(auth[1]);
      const allImages = await Image.findAll();
      res.send(allImages);
    } catch (error) {
      res.status(400).send("Invalid JWT token");
    }
  } else {
    res.status(401).send({ message: "Please supply valid credentials" });
  }
});

This is the router/auth.js

const { Router } = require("express");
const { toJWT, toData } = require("../auth/jwt");

const router = new Router();

router.post("/auth/login", async (req, res, next) => {
  try {
    const { email, password } = req.body;
    if (!email || !password) {
      return res.status(400).send("Email and password required");
    } else {
      res.send({ jwt: toJWT({ userId: 1 }) });
    }
  } catch (error) {
    console.log(error.message);
    next(error);
  }
});

module.exports = router;

This is the auth/jwt.js

const jwt = require("jsonwebtoken");

const secret =
  process.env.JWT_SECRET || "e9rp^&^*&@9sejg)DSUA)jpfds8394jdsfn,m";

const toJWT = (data) => {
  return jwt.sign(data, secret, { expiresIn: "2h" });
};

const toData = (token) => {
  return jwt.verify(token, secret);
};

module.exports = { toJWT, toData };

Hope somebody can help :)

I'm doing one of my first exercises on authorization, but I can't understand what I'm doing wrong with this one. I'm trying to validate the JWT token, but it gives me back that it's invalid

I get the token with httpie:

http POST :4000/auth/login [email protected] password=test

And then I try validating with httpie:

http GET :4000/images authorization:"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsImlhdCI6MTY0ODgyMDI3MCwiZXhwIjoxNjQ4ODI3NDcwfQ.AhArOvQTaJ7ohbPiyGiGTK5pFMWqjbZ5Kj9q2hXEhXU"

Which gives me: Invalid JWT token

This is my router/images.js

const { Router } = require("express");
const Image = require("../models").image;
const router = new Router();
const toData = require("../auth/jwt");

router.get("/images", async (req, res) => {
  const auth =
    req.headers.authorization && req.headers.authorization.split(" ");
  if (auth && auth[0] === "Bearer" && auth[1]) {
    try {
      const data = toData(auth[1]);
      const allImages = await Image.findAll();
      res.send(allImages);
    } catch (error) {
      res.status(400).send("Invalid JWT token");
    }
  } else {
    res.status(401).send({ message: "Please supply valid credentials" });
  }
});

This is the router/auth.js

const { Router } = require("express");
const { toJWT, toData } = require("../auth/jwt");

const router = new Router();

router.post("/auth/login", async (req, res, next) => {
  try {
    const { email, password } = req.body;
    if (!email || !password) {
      return res.status(400).send("Email and password required");
    } else {
      res.send({ jwt: toJWT({ userId: 1 }) });
    }
  } catch (error) {
    console.log(error.message);
    next(error);
  }
});

module.exports = router;

This is the auth/jwt.js

const jwt = require("jsonwebtoken");

const secret =
  process.env.JWT_SECRET || "e9rp^&^*&@9sejg)DSUA)jpfds8394jdsfn,m";

const toJWT = (data) => {
  return jwt.sign(data, secret, { expiresIn: "2h" });
};

const toData = (token) => {
  return jwt.verify(token, secret);
};

module.exports = { toJWT, toData };

Hope somebody can help :)

Share Improve this question asked Apr 1, 2022 at 13:49 gabriel_smtgabriel_smt 211 gold badge1 silver badge6 bronze badges 1
  • Have you tried to just finish after validating the token (maybe return the user id or something), the try catch block encloses the image operations as well, so it might actually be an error happening there. Also maybe output the error that happened. – ChristianM Commented Apr 1, 2022 at 14:05
Add a ment  | 

1 Answer 1

Reset to default 2

Inside your router/images.js file, it looks like you are not requiring the toData method correctly. You are requiring the module with two exported functions, so if you use destructuruing, you would have to access your toData method like you did inside of auth.js.

Change line 4 of router/images.js to:

const { toData }  = require("../auth/jwt");

When you require the auth/jwt file with a single const that is not destructured, you would access the exported methods of that file with dot notation:

const jwt = require("../auth/jwt");

jwt.toData(auth[0]);
发布评论

评论列表(0)

  1. 暂无评论