Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify a JWT token string, containing 'Bearer ' with NodeJS

Tags:

node.js

jwt

I send a header in a recommended form Authorization: Bearer <token>.

As it looks, token string, which is 'Bearer <token>', is not a token, but needs the 'Bearer ' substring to be removed first to get the token string itself.

I wonder, if it's a regular practice to remove it manually from code, like this:

const token = authHeaderValue.replace('Bearer ', '')

before decoding and verifying it?

Why do I need this 'Bearer ' string in my custom application?

like image 983
Sergei Basharov Avatar asked Oct 12 '16 07:10

Sergei Basharov


2 Answers

I use this technique.

// Header names in Express are auto-converted to lowercase
let token = req.headers['x-access-token'] || req.headers['authorization']; 

// Remove Bearer from string
token = token.replace(/^Bearer\s+/, "");

if (token) {
  jwt.verify(token, config.secret, (err, decoded) => {
    if (err) {
      return res.json({
        success: false,
        message: 'Token is not valid'
      });
    }
    req.decoded = decoded;
    next();
  });
} else {
  return res.json({
    success: false,
    message: 'Token not provided'
  });
}

Here we are stripping off any Bearer string in front of JWT, using a regular expression. If any whitespace is included, it is stripped too.

like image 137
Naren Yellavula Avatar answered Nov 16 '22 04:11

Naren Yellavula


The value Bearer in the HTTP Authorization header indicates the authentication scheme, just like Basic and Digest. It's defined in the RFC 6750.

An application can support multiple authentication schemes, so it's always recommended to check the authentication schema first.

In a token based authentication, first ensure that the Authorization header contains the Bearer string followed by a space. If not, refuse the request. If Bearer followed by a space has been found, extract the token that must be just after the space character.

See this answer for further details on the Bearer authentication scheme.

like image 27
cassiomolin Avatar answered Nov 16 '22 04:11

cassiomolin