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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With