0

I am using jsonwebtoken library to sign and create JWTs to be used for API security,

The code looks to be working fine when I try to verify the signature with a valid JWT_SECRET_TOKEN and throws an error when I use a wrong JWT_WRONG_TOKEN

However when I copy the token and put it in https://jwt.io/ ,
It shows Signature Verified for any secret that I put in.

Following is my code -

const jwt = require('jsonwebtoken');

const JWT_SECRET_TOKEN = 'secret';
const JWT_WRONG_TOKEN = 'test';
const DATA = 'My Test Data';

// Equivalent to 1 Hour
// Data should be an Object to be signed
let token = jwt.sign({data: DATA}, JWT_SECRET_TOKEN, { expiresIn: 60 * 60 * 1 });

console.log("Encoded token => ",token);
console.log("token => "+JSON.stringify(jwt.decode(token)));

jwt.verify(token, JWT_SECRET_TOKEN, function (err, decoded) {
//jwt.verify(token, JWT_WRONG_TOKEN, function (err, decoded) {
    if (err) {             
        console.log('Error => ', err);

        if (err.name === 'TokenExpiredError') {
            console.log("AUTH_EXPIRED");
        } 
        else if (err.name === 'JsonWebTokenError') {
            console.log("JWT_ERROR");
        }
        else if (err.name === 'NotBeforeError') {
            console.log("JWT_NOT_ACTIVE");
        } else {
            console.log("ERR_ON");
        }

    } else {
        console.log('Success => ', decoded)
    }
  })

Reference -
1. https://www.npmjs.com/package/jsonwebtoken
2. https://jwt.io/

What am I doing wrong?
How do I resolve it?

Dev1ce
  • 5,390
  • 17
  • 90
  • 150

1 Answers1

1

You just signed some data with a private key, anyone can read data with or without a private key, but cannot change its content. That is how JWT works.

On jwt.io you entered some new secret and website responded Signature Verified which means your data is now signed with a new secret, and the token is regenerated, that token should not pass on your backend since its invalid.

DedaDev
  • 4,441
  • 2
  • 21
  • 28
  • So if my data is encrypted safely to be shared in the token data, And as long as my secret key is not known to anyone, is my method is safe to be used? – Dev1ce Apr 03 '19 at 03:02
  • yeah, search for library jose or node-jose, which includes other types of JSON-based data structures like JWE (json web encryption). – DedaDev Apr 03 '19 at 03:54
  • Ok so only my data needs to be properly encrypted, rest JWT signature creation and Verification code is correct? – Dev1ce Apr 03 '19 at 03:56
  • 1
    You can implement your own encryption and place encrypted data inside JWT payload but that is not best practice. I would suggest you to look at node-jose documentation it's easy as `jose.JWE.createEncrypt(key).input(data)` to encrypt `jose.JWE.createDecrypt(key).decrypt(data)` to decrypt – DedaDev Apr 03 '19 at 04:06