REST — Token based authentication (jwt)

Separation of client and server

Statelessness

Access tokens

Implementing token based authentication

const express = require('express');
const router = express.Router();
const password_hash = require('password-hash');
const jwt = require('jsonwebtoken');
const app = express();router.post('/api/user/validate', (req, res) => {
let curPass = req.body.password;
var pass_hash = "";
User.findOne({email: req.body.email},
(err, users)=>{
if(err){
res.json({success: false, msg: "Invalid", data: []});
}
if(users){
pass_hash = users.password_hash;
verification = password_hash.verify(curPass, pass_hash);
if(verification){
// token
const payload = {
role: users.role,
user_id: users._id
};
var token = jwt.sign({
exp: Math.floor(Date.now() / 1000) + (60 * 60), // 1 hour
data: payload
}, 'top-secret');
res.json({success: true, msg: "Login Successful", token: token});
}
else{
res.json({success: false, msg: "Invalid password", data: []});
}
}
else{
res.json({success: false, msg: "Invalid email id", data: []});
}
});
});
{
"success": true,
"msg": "Login Successful",
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAasdagdfxg"
}
https://www.xyz.com/api/userREQUEST HEADERS
token: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAasdagdfxg
// jwt middleware to verify token
router.use((req, res, next)=>{
var token = req.body.token || req.headers['token'];
if(token){
jwt.verify(token, 'top-secret', (err, decoded)=>{
if(err){
return res.json({success: false, msg: 'Token not valid or expired', data: []});
}
else{
req.decoded = decoded;
next();
}
});
}
else{
return res.status(403).json({success: false, msg: 'No token provided', data: []});
}
})
// get logged user information
router.get('/user', (req, res) => {
User.find({_id: req.decoded.data.user_id}, (err, user)=>{
if(!err){
res.json({success: true, msg: "", data: user});
}
else{
res.json({success: false, msg: "Invalid user", data: []});
}
}).select('-password_hash');
});
 https://github.com/adipixel/expense-tracker/blob/master/routes/api_route.js

--

--

--

Software Engineer — Frontend

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Front-End developer interview preparation day 5

How to Merge Objects with the Object Spread Operator

How

How My Tech Journey Started

Industrial use-cases of JavaScript

Angular: Top 4 Front-End Developer Opinions

How to create a page with github.io

How to Create a Marketplace with Medusa Part 2: Make Orders Specific to Vendors

How to configure UTM parameters linking for Android in React Native apps — 1x07

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aditya Mhamunkar

Aditya Mhamunkar

Software Engineer — Frontend

More from Medium

Deploying Node.JS MongoDB application

Develop Backend Functions using node js