javascriptnode.jsrestify

I need to replace Bearer from the header to verify the Token


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

Solution

  • 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) {
         }
       }
    }