'Verify a JWT token string, containing 'Bearer ' with NodeJS
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?
Solution 1:[1]
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.
Solution 2:[2]
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.
Solution 3:[3]
Authentication header request have a format defined in IETF.
i.e. Authentication :
Type consists of following: Bearer, error_code, error_description.
We can send several types at once by delimiting it by ',' character.
Bearer is an Authentication access type.
Solution 4:[4]
i use split function to extract token
const bearerHeader = req.headers['authorization'];
if(! bearerHeader ){
return res.sendStatus(403);
}
else
{
const bearerToken = bearerHeader.split(' ')[1];
let data = await jwt.verify(bearerToken,secretkey);
}
Solution 5:[5]
const bearerToken = token.split(' ')[1];
Here is the solution. And it will fix your issue. You just need to split function. And in code given below, i show you when to use split function for a specific token.
Cheers!
verifyToken = (req, res, next) => { res.header( "Access-Control-Allow-Headers", "*" ); let token = req.headers["authorization"];
if (!token) {
return res.status(403).send({ message: "No token provided!" });
}
**const bearerToken = token.split(' ')[1];** Here is the solution. And it will fix your issue. You just need to split function.
jwt.verify(bearerToken, config.secret, (err, decoded) => {
if (err) {
return res.status(401).send({ message: "Unauthorized Token!" });
}
req.userId = decoded.id;
req.token = token;
next();
});
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |
Solution 2 | Jan Pokorný |
Solution 3 | Community |
Solution 4 | krishnazden |
Solution 5 |