You can use JsonWebtoken npm package to implement jwt based authentication in your express App.
This is how authentication works :
Set Token in login.service.js file or where ever required with appropriate data as payload :
const token = jwt.sign('payload', 'secret key',
{ expiresIn: 60*60 });
how token looks: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjoiYW5pcyIsImVtYWlsIjoic29tZW1lYWlsLmNvbSIsImlhdCI6MTUxNjIzOTAyMn0.FyDrUNkvDi82lYv8JioAB9Ih8vyn6Y6mY8PpUiIz8nY
You can decode it by pasting the token on jwt.io website.
Usually we store the token in cookies(before sending response in login.router.js file set the cookie as token) :
router.get('/auth/google/callback', (req, res, next) => {
loginCtrl.redirectGoogle(req, res, next).then((result) => {
res.cookie('userToken', token);
res.redirect('/#/app/home');
}, (err) => {
console.log("Error in authentication **[ ", err, " ]** ");
res.redirect(500, '/#/login');
});
now write a middleware(authentication) that is called before every API request(authentication.router.js file).
router.use((req, res, next) => {
try {
const token = req.cookies.currentUser;
// console.log('cookie', token);
// to decode token
if (token) {
authCtrl.verifyToken(token, (err, decoded) => {
if (err) {
res.clearCookie(config.UserToken);
res.status(401).json({ error: ' Session Timeout... Please login again' });
// console.log('token expired');
// res.redirect('/#/login');
} else {
req.user = decoded;
next();
}
// console.log('Token verified');
// res.cookie(config.cookie.name,successResult.authToken);
});
} else {
// if there is no token
// return an error
return res.status(403).send({
message: 'User not authenticated.',
});
}
} catch (error) {
// console.log(error);
return error;
}
});
- Inside verifyToken function which is inside auth.controller.js file we
decode the token :
const jwt = require('jsonwebtoken');
const verifyToken = (usertoken, done) => {
jwt.verify(usertoken,'secret key', (err, res) => {
if (err) {
return done(err);
}
return done(null, res);
});
};
module.exports = {
verifyToken,
};
Now you API endpoints are are protected with authentication. Make sure The authentication middleware is place at top in app.js file.
router.use('/login', require('./modules/login'));
router.use('/logout', (req, res) => {
res.clearCookie(userToken);
res.redirect('/');
});
router.use(require('./modules/authentication'));
// Each Module to be placed after this
router.use('/communityMembers',require('./modules/communitymember'));