Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  127] [ 7]  / answers: 1 / hits: 30595  / 7 Years ago, thu, may 11, 2017, 12:00:00
bearer = bearerHeader.replace(Bearer,);
jwt.verify(bearer, 'super_secret', function (err, decoded) {
console.log(err);
console.log(decoded);
});


Here is my code. Whenever I try to verify Token. I want to replace Bearer from header to verify only token. it will always goes to 'err' if a take Bearer. when i remove the Bearer from header i will work perfect. anyone please help me to solve this. Is there any way to solve this problem?



Output:



  { 
[JsonWebTokenError: invalid token] name: 'JsonWebTokenError',
message: 'invalid token'
}

undefined

More From » node.js

 Answers
9

if bearerHeader is something like Bearer 456513 then your code



bearerHeader.replace(Bearer,);


will result: 456513 (there are space before the token)



bearerHeader.replace('Bearer ',''); 


may solve your issue but I recommend to verify the authentification scheme first (Bearer term is really Bearer):



 var parts = bearerHeader.split(' ');
if (parts.length === 2) {
var scheme = parts[0];
var credentials = parts[1];

if (/^Bearer$/i.test(scheme)) {
token = credentials;
//verify token
jwt.verify(token, 'super secret', function(err, decoded) {
}
}
}

[#57821] Monday, May 8, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
melody

Total Points: 295
Total Questions: 97
Total Answers: 101

Location: Aruba
Member since Fri, Jun 24, 2022
2 Years ago
;