Home > Blockchain >  JsonWebToken "invalid signature" in nodejs
JsonWebToken "invalid signature" in nodejs

Time:03-26

I am quite new to authentication in express/node and I wrote a login system that returns a jwt token to the frontend. However, when I try to authenticate the user with this token on other routes, like a route for uploading a new post, I always get a "JsonWebTokenError: Invalid Signature" error.

I did verify the integrity of the token using jwt.io, so to my understanding the token itself seems to be alright.

This is where the token is signed upon logging in:

import express from "express";
import jwt from "jsonwebtoken";

router.post("/login", (req, res) => {

//left out all the validation

const token = jwt.sign({ _id: "currentUserId_123" }, "environtmentSecret");
  res.send({ token: token });
});

The token is then used for authentication when for example trying to upload a new post:

router.post("/upload", verify, async (req, res) => {

//validates input and saves to database here

res.status(200).send({message: "Created new post!"});
});

the validation itself happens in the verify middleware that looks like this:

import jwt from "jsonwebtoken";

function verify(req, res, next) {
  const token = req.header("auth");

  if (!token) return res.status(401).send({ message: "Access Denied" });

  try {
    const payload = jwt.verify(token, "environtmentSecret"); //the error seems to occur here while verifying
    req.user = payload;
 
    next();
  } catch (e) {
    res.status(400).send(e); //this returns the specified error
  }
}

export { verify };

I hope I provided enough information about my project, if that's not the case feel free to ask for any more.

Thank you in advance, any help is strongly appreciated!

CodePudding user response:

The problem could be if you are using one value to sign the jwt and another to verify it. What I mean by that is that here you sign it with "environtmentSecret"

const token = jwt.sign({ _id: "currentUserId_123" }, "environtmentSecret");

And later you use

const payload = jwt.verify(token, process.env.TOKEN_SECRET);

Where you get the error, so check if process.env.TOKEN_SECRET is equal to "environtmentSecret". It is also could practice to not display the secret. So maybe change this sign part to this:

const token = jwt.sign({ _id: "currentUserId_123" }, process.env.TOKEN_SECRET);

CodePudding user response:

After a total of 3 days and 6 1/2 hours of looking for the error, I finally found it.

The problem was that the secrets used for signing and verifying the token on my machine were different than the ones used in the cloud where I host my project. So naturally, couldn't verify the token due to their differing.

This was a problem related to configuration, and not to programming.

Still, much thanks to all of you for trying to help me

  • Related