Let me tell you the process of using jsonwebtokens.
Process:
- we require them after installing the jsonwebtoken dependency to our initial project.
npm i jsonwebtoken
- we also install bcrypt along with it, inorder to hash our passwords with this package.
npm i bcrypt
- after adding required route handlers,and the models to server component.
- inside the route handlers(i.e. controllers) create an token object to get the jwt for the specified user id whenever he/she logins.
const token = jwt.sign({ _id: user._id }, process.env.JWT_SECRET, { expiresIn: "1h" });
- then sends the token as a response body to the client
res.header('auth-token', token).send(token);
- and this new token generation is formed everytime the user logins.
- this authentication helps to access the protected routes of particular users who has access to particualar routes after login.
- like after logging in to instagram account user can access posts section.
- for this verifyToken function helps to access as we pass that func as a param to the posts route
const express = require('express');
const verifyToken = require('../utils/verifyToken');
const router = express.Router();
router.get('/', verifyToken, (req, res) => {
res.send('This is a protected post');
});
module.exports = router;
- this verifyToken method requires the respective module and performs the verification process like this
const jwt = require('jsonwebtoken');
module.exports = function(req, res, next) {
const token = req.header('auth-token');
if (!token) return res.status(401).send('Access denied');
try {
const verified = jwt.verify(token, process.env.JWT_SECRET);
req.user = verified;
next();//calls the next middleware function
} catch (err) {
res.status(400).send('Invalid token');
}
};
from above we define the object token that is fetched from the request header.
if token is not present we get response "access denied." and not redirect to posts page.
and if we found the token valid, it will return the decoded payload(usually has user's id and details), ans allows to the protected route that is posts page.
- To test this all ,you can use an extension called Thunder Client inorder to see server side checks, if you didn't set up frontend.
It is usual to say that ,start working on backend first to set things up and understand it's working fine.If ur good to go then go on implementing the frontend based on the schema reference.
Which should match ultimately.
For any further queries or discussions reach mme out in comment section.Consider this as a review or quick revision post.
Happy Developing!
Top comments (0)