-1

This is how my token is generated:

const generate_web_token = function (user) {
  const token = jwt.sign(
    {
      _id: user._id,
      email: user.email,
      password: user.password,
    },
    process.env.SECRET_TOKEN_KEY
  );
  return token;
};

Now, when the clients sends a request to the server, how can the server extract the _id field for example?

1 Answers1

4

The header and claims are just (url-safe) base64 encoded. Only the signature is encrypted and encoded. So you could just split it on the . and decode the middle part as those are the claims.

const jwt = `eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c`

const claims = atob(jwt.split('.')[1])

console.log(claims)

You can read more about tokens here https://jwt.io/.

Since you are using a library to handle the tokens for you, it would be probably best to use its features to do that.

var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
// some time later
var decodedClaims = jwt.verify(token, 'shhhhh');
console.log(decodedClaims.foo) // bar
The Fool
  • 16,715
  • 5
  • 52
  • 86