Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
JWT token invalid, but why

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=test@test.com 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 :)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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]);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda