Create Authentication Tokens
Let's create authentication tokens in the coming video!
To create and verify authentication tokens, you will need a new package:
npm install jsonwebtoken
Then import it in your user controller:
const jwt = require('jsonwebtoken');
And use it in your login
function:
exports.login = (req, res, next) => {
User.findOne({ email: req.body.email }).then(
(user) => {
if (!user) {
return res.status(401).json({
error: new Error('User not found!')
});
}
bcrypt.compare(req.body.password, user.password).then(
(valid) => {
if (!valid) {
return res.status(401).json({
error: new Error('Incorrect password!')
});
}
const token = jwt.sign(
{ userId: user._id },
'RANDOM_TOKEN_SECRET',
{ expiresIn: '24h' });
res.status(200).json({
userId: user._id,
token: token
});
}
).catch(
(error) => {
res.status(500).json({
error: error
});
}
);
}
).catch(
(error) => {
res.status(500).json({
error: error
});
}
);
}
Here:
Use jsonwebtoken's
sign
function to encode a new token.That token contains the user's ID as a payload.
Use a temporary development secret string to encode your token (to be replaced with a much longer, random string for production).
Set the token's validity time to 24 hours.
Send the token back to the front end with your response.
You can now use the Chrome DevTools Network tab to check that, once logged in, every request coming from the front end contains an "Authorization" header, with the keyword "Bearer" and a long encoded string. This is your token.
Let's Recap!
JSON web tokens are encoded tokens that can be used for authorization.
The
jsonwebtoken
package'ssign()
method uses a secret key to encode a token which can contain a custom payload and be valid for a limited time.
In the next and final chapter of this part, you will create a piece of middleware to check for and verify this token and its contents to ensure that only authorized requests get access to the routes you want to protect.