December 18, 2021 01:14 pm GMT
Original Link: https://dev.to/deepakjaiswal/secure-our-website-using-jwt-json-web-token-in-nodejs-or-expressjs-5a7d
Secure our website using JWT (JSON Web Token) in nodeJS or expressJS
here we are using JWT to secure our application or website from unauthenticated user they try to access our data.
In npmjs a library named is
jsonwebtoken
npm i jsonwebtoken
if we only check user isAuthenticated or not we simply pass the middleware in between request and response
auth.js
export default function getTokenFromUser(req: Request) {
const authorization = req.headers.token;
var decoded = jwt.verify(authorization, 'secret');
if (!decoded) {
throw new TokenError("No Authorization Header");
}
try {
const token = decoded?.split("User data ")[1];
return token;
} catch {
throw new TokenError("Invalid Token Format");
}
}
we simple pass this auth of in between req,res
app.post('/api/post',auth,(req,res)=>{//if some operation on code we use middlewareconst token=jwt.sign({ data: 'your data to store as token'}, 'secret', { expiresIn: '1h' });res.header('token',token).send("success")});
we ensure that you can save your secret key in your config file.
Original Link: https://dev.to/deepakjaiswal/secure-our-website-using-jwt-json-web-token-in-nodejs-or-expressjs-5a7d
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To