I need to replace Bearer from the header to verify the Token
Asked Answered
M

5

19
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
Methyl answered 11/5, 2017 at 12:25 Comment(0)
T
41

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) {
     }
   }
}
Tinware answered 11/5, 2017 at 12:32 Comment(0)
H
5

Try this

bearer = bearerHeader.replace(/^Bearer\s/, '');
    jwt.verify(bearer, 'super_secret', function (err, decoded) {
                        console.log(err);
                        console.log(decoded);`
    }
Holophytic answered 4/10, 2019 at 0:21 Comment(0)
V
4

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", "");
Voluntaryism answered 1/11, 2020 at 13:17 Comment(0)
P
2

you should have to pass space after Bearer

var token = req.headers.authorization.replace('Bearer ', '');
Prudery answered 30/9, 2021 at 5:51 Comment(0)
F
1

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
Floatplane answered 6/7, 2023 at 10:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.