Reputation: 107
Im building a application where i want to use jwt-tokens for authentication. i followed the tutorial on this website: https://stormpath.com/blog/nodejs-jwt-create-verify
The problem is when i want to use the verify function i get this error: JwtParseError: Signature verification failed.
And i cant figure out what im doing wrong.
The moment i create the token i save it in my database along with the secret key. Then i sent this token to the browser. The browser sents this token back, at that moment i search for the token in my database. Then i use the token and the secretkey that was stored with it to verify. At that moment i get the error.
Code when i build token and store it:
let secretkey = Jwt.createKey();
let token = Jwt.getToken(message.id, message.adress, 0);
const mySql = new mysql();
mySql.insertToken(message.id, token, secretkey);
Code when i get token and verify:
mySql.getFromDB(token,(err, result)=>{
let body = result[0];
const Jwt = new jwt();
let secretkey = Buffer.from(body.secretkey, 'base64');
let jwtcheck = Jwt.checkJWT(body.token, secretkey);
//console.log(jwtcheck);
The other strange thing is that when i run the jwt.io debugger. I enter my token and it says verification failed, but when I click on the "secret base64 encoded" button, it says signature verified.
Pls can someone help me?
Thanks
update*
code for jwt.getToken:
createKey()
{
this.secretkey = uuid();
return secretkey;
}
createClaims(ssub, iiss, ppermissions)
{
let claims = {
sub: ssub,
iss: iiss,
permissions: ppermissions
};
return claims;
}
createJWT(secretkey, sub, iss, permissions)
{
const jwt = nJwt.create(this.createClaims(sub, iss, permissions), secretkey);
return jwt;
}
getToken(sub, iss, permissions)
{
const jwt = this.createJWT(this.secretkey, sub, iss, permissions);
const token = jwt.compact();
return token;
}
Upvotes: 2
Views: 3674
Reputation: 107
Soo i figured it out. The moment i create my secret. i had to encode it to a base64, so the method would look like this:
createKey()
{
this.secretkey = uuid();
console.log(secretkey);
this.secretkeybase = Buffer.from(secretkey).toString('base64');
return this.secretkeybase;
}
At this moment the token gets verified.
Upvotes: 4
Reputation: 336
I belive that you must explicity define a secret key, like Jwt.createKey("you-secretkey-here");
and use the same key in Jwt.checkJWT(body.token, "you-secretkey-here");
. Try to pass the same secret key from the Jwt.createKey
to Jwt.checkJWT
function.
Upvotes: 0