Home > other >  Node/jsonwebtoken- jwt.sign() does not add in payload to my token
Node/jsonwebtoken- jwt.sign() does not add in payload to my token

Time:11-25

I'm building an API in Node and I've set up const jwt = require('jsonwebtoken') to use JWTs. The problem is the token that is generated does not include the payload in it. I've tried decoding it using express-jwt and jsonwebtoken.verify().

When I decode on JWT.io using the secret/public keys, signature is verified and all token details are correct, but there is no payload.

Here is my code.

user.js

const jwt = require("jsonwebtoken")
const { secretKey } = require("../keyConfig")
const createToken = (user) => {
  return jwt.sign({ id: user.id }, secretKey, {
    algorithm: "RS256",
    expiresIn: 12000,
    subject: "Login details",
  })
}

const token = createToken(user)

authMiddleware.js

const { expressjwt: jwt } = require("express-jwt")
const js = require('jsonwebtoken')

const getTokenFromHeader = (req) => {
  if (
    req.headers.authorization &&
    req.headers.authorization.split(" ")[0] === "Bearer"
  ) {
    const token = req.headers.authorization.split(" ")[1]
    const de = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString())
    const ver = js.verify(token, publicKey)
    return token
  }
}

const checkIfAuth = jwt({
  algorithms: ["RS256"],
  secret: publicKey,
  getToken: getTokenFromHeader,
})

I recreated the error by building a new project. Repeated the code above and had the same issue. Token is created, all details are correct but no payload.

Here is the decoded token:

{ "iat": 1668995400, "exp": 1669007400, "sub": "Login Details" }

CodePudding user response:

I'm not sure how you are using the authMiddleware.js in your question. But when I add a middleware in express doing the same thing and making a request from postman it all works fine.

Maybe you can use this to figure out why your code doesn't work.

const jwt = require("jsonwebtoken");
const express = require("express");
const app = express();

const SECRET = "qwerty";

const token = jwt.sign({ id: 1234 }, SECRET);

// Copy the value and use in postman
console.log(token);

// Middleware
const getTokenFromHeader = (req, res, next) => {
  if (
    req.headers.authorization &&
    req.headers.authorization.split(" ")[0] === "Bearer"
  ) {
    const token = req.headers.authorization.split(" ")[1];
    const de = JSON.parse(
      Buffer.from(token.split(".")[1], "base64").toString()
    );
    // verify is asyncronous
    jwt.verify(token, SECRET, (err, decoded) => {
      if (err) {
        next();
      }
      res.tokenPayload = decoded;
    });
  }
  next();
};
app.use(getTokenFromHeader);

app.get("/test-token", (req, res) => {
  res.status(200).send(res.tokenPayload);
});

app.listen(3000, () => {
  console.log("Listening on port 3000");
});

request

  • Related