Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 525
Nainesh Raval Avatar asked May 11 '17 12:05

Nainesh Raval


People also ask

How do you authenticate a bearer token?

Bearer tokens enable requests to authenticate using an access key, such as a JSON Web Token (JWT). The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value.

How do I send a bearer token in header?

To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.

Why do we add bearer before token?

Bearer Token A security token with the property that any party in possession of the token (a “bearer”) can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).


1 Answers

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) {
     }
   }
}
like image 125
Fetrarij Avatar answered Oct 06 '22 23:10

Fetrarij