Verify a JWT token string, containing 'Bearer ' with NodeJS
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.
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.