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?
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.