REST — Token based authentication (jwt)

Aditya Mhamunkar
Feb 8, 2018 · 4 min read

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

Aditya Mhamunkar

Written by

Uniting the world under the hood of a web browser by developing web application services.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade