Authenticate Node JS Rest APIs With JWT
Let's See How We Can Authenticate Node JS Rest APIs With JWT Package
Firstly install the jwt package in your node js project via below command:
$ npm install jsonwebtoken
Create User Token
For creating token we can manage it in middleware.
Let's say create AuthMiddleware.js file:
const jwt = require('jsonwebtoken');
const createUserToken = async(id,email) => {
try{
const token = jwt.sign({"user_id":id, "email": email}, process.env.JWT_TOKEN_KEY, {
expiresIn: process.env.JWT_TOKEN_EXP //2h, 30d
})
return token
}catch(err){
return ''
}
}
module.exports = {
createUserToken
}
Now in controller we can call this function for create token.
Let's say we have UserControoler.js file inside which we are creating user token:
const AuthMiddleware = require('../middlewares/AuthMiddleware');
const create = async(req, res, next) => {
try{
console.log('User create api called.');
let token = await AuthMiddleware.createUserToken(1,'email@test.in');
console.log(token);
res.send(token);
}catch(err){
console.log(err.message);
}
}
module.exports = {
create
}
Verify User Token & Get Data From Token
Inside our Middleware file we can verify user token and get user data, Here is the below code:
const verifyUserToken = (req, res, next) => {
try{
let token = fn.getReqToken(req);
if(!token) return ResponseMiddleware(req,res,messages('en')['token_required'],401);
const decoded = jwt.verify(token, process.env.JWT_TOKEN_KEY)
//console.log(decoded)
req.user = decoded
next()
}catch(err){
//console.log(err);
return ResponseMiddleware(req,res,'User token is invalid.',401)
}
}
That's it.
Happy Coding 💻
Comments
Post a Comment