JWT is used to secure web token. JWT stands for JSON Web token.
JWT is used to encrypt the token so that no one hacks the token.
How to install JSON Web Token in Nodejs?
npm i jsonwebtoken
How to create JSON Web Token token in Nodejs?
Suppose, you create createjwt.js file
include jsonwebtoken through require method
var jwt = require('jsonwebtoken');
module.exports.create_jwt_token= async ()=>{
let role=1;
let email='john@abc.com'
let token = jwt.sign({role:role,email:email}, 'sh233444hh'); // save token into database
console.log("token:-",token);
}
Now, create the index.js file and include the createjwt.js file
var createjwt = require('./createjwt');
createjwt.create_jwt_token();
Output:-
token:- eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoxLCJlbWFpbCI6ImpvaG5AYWJjLmNvbSIsImlhdCI6MTYxMDE3MTk2N30.IGVdnytBjesv4PZld7TZuwqzfGoxL9DOYKK72QfoD0U
How to verify JWT token in Nodejs?
Suppose, you create verifyjwt.js file
include jsonwebtoken through require method
module.exports.verify_jwt_token= async (token)=>{
jwt.verify(token, 'sh233444hh', async function(err, results) {
if(err){
console.log("error+++",err);
}else{
console.log(results);
}
})
}
Now, create the index.js file and include the verifyjwt.js file
var verifyjwt = require('./verifyjwt');
var token="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoxLCJlbWFpbCI6ImpvaG5AYWJjLmNvbSIsImlhdCI6MTYxMDE3MTk2N30.IGVdnytBjesv4PZld7TZuwqzfGoxL9DOYKK72QfoD0U";
var output=verifyjwt.verify_jwt_token(token);
console.log(output);
Output:-
{ role: 1, email: ‘john@abc.com’, iat: 1610173305 }