OpenClassrooms devient une université américaine accréditée.
Découvrez ce que cela change pour vousTable des matières
- Partie 1
Build a Simple Express Server
- Partie 2
Build a RESTful API
- Partie 3
Make Your API Secure
- Partie 4
Add Image Upload to Your API
Create Authentication Tokens
#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
signfunction 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
jsonwebtokenpackage'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.
- Formations jusqu’à 100 % financées
- Date de début flexible
- Projets professionnalisants
- Mentorat individuel