18
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
Sangwin Gawande
  • 7,658
  • 8
  • 48
  • 66
Nainesh Raval
  • 211
  • 1
  • 3
  • 10

5 Answers5

39

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) {
     }
   }
}
Fetrarij
  • 7,176
  • 3
  • 27
  • 35
5

Try this

bearer = bearerHeader.replace(/^Bearer\s/, '');
    jwt.verify(bearer, 'super_secret', function (err, decoded) {
                        console.log(err);
                        console.log(decoded);`
    }
Kingsolo50
  • 63
  • 1
  • 3
3

You can try to split() the string on spaces and discard the first element

// OPTION 1
bearerHeader.split(" ")[1];

or you can simple cut Bearer from the string

// OPTION 2
bearerHeader.replace("Bearer", "");
m02ph3u5
  • 3,022
  • 7
  • 38
  • 51
giovaniZanetti
  • 452
  • 4
  • 7
2

you should have to pass space after Bearer

var token = req.headers.authorization.replace('Bearer ', '');
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
0

Another potential solution if you need to support multiple authorisation schemes or if you are unsure if bearer will be provided or not.

const authToken = req.headers.authorization
const [token, ...rest] = authToken.split(' ').reverse()

With this code, 12345 will be returned for the following test data:

  • 12345
  • Bearer 12345
  • Basic 12345
Patrick
  • 6,495
  • 6
  • 51
  • 78