Authenticate With Json Web Token
As web developers or app developers we need to authenticate users. We can do it several ways.. In this note im going to tell how to authenticate users in node js and express backend using json web token library. This is very useful to make api and this method works with web sites as well as apps. This is useful to mean,mern,mevn stacks.
First we need to initialize node js app in working directory
npm init
Then we want to add libraries using following command
npm install express cors body-parser mongoose jsonwebtoken
- Express is our main server library for managing our middlewares and processes.
- Cors used to manage our cors policies.
- Body parser is used to get json type request bodies.
- Mongoose used to work with mongo db. Because mongoose library is a smart library for mongo db.
- Json web token is used to sign our token using preferred hash.
Then we can start coding. First we need to initialize an express web application in index.js.
const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const cors = require(‘cors’);
const mongoose = require(‘mongoose’);const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.use(bodyParser.json());app.listen(port,()=>{
console.log(‘Server Started!’);
})
Then we can connect our application to mongo db adding following codes
const mongo_url = "mongodb://localhost:27017/texting_quiz";mongoose.connect(mongo_url,{
useUnifiedTopology:true,
useNewUrlParser:true
})const connection = mongoose.connection;connection.once("open",()=>{
console.log("Mongo DB Connection Established Success!")
})
then I create folder named routes. then add new file named as Authentication.js. this is our file that conitains middlewares. then import that to our index.js file. then out main index.js file looks like this
index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');const app = express();
const port = process.env.PORT || 3000;
app.use(cors());
app.use(bodyParser.json());const mongo_url = "mongodb://localhost:27017/texting_quiz";mongoose.connect(mongo_url,{
useUnifiedTopology:true,
useNewUrlParser:true
})const connection = mongoose.connection;connection.once("open",()=>{
console.log("Mongo DB Connection Established Success!")
})const Authentication = require('./routes/Authentication');app.use('/api/auth',Authentication);app.listen(port,()=>{
console.log('Server Started!');
})
then we can create schema for new user
i’m create new folder named as models
then i create UserSchema.js inside the models folder.
const mongoose = require('mongoose')
const Schema = mongoose.Schemaconst UserSchema = new Schema({
f_name:String,
l_name:String,
email:String,
password:String
})module.exports = mongoose.model("User",UserSchema)
then i create functions folder and create AuthFunctions.js file inside it. it will useful to manage reusable authentication functions
we introduce secret key inside it
const jwt = require(“jsonwebtoken”);function getSecret(){
return “this is secret key”;
}module.exports = {getSecret}
then i introduce requests for authentication route
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');const {getSecret} = require('../functions/AuthFunctions');const UserSchema = require("../models/UserSchema");router.post('/login',(req,res)=>{
})router.post('/register',(req,res)=>{
})router.get('/access',(req,res)=>{
})module.exports = router;
we have three routes
api/auth/login
api/auth/register
api/auth/access
login request need to check if user available in mongo db and if alailable user then it send token
router.post('/login',(req,res)=>{
UserSchema.find({email:req.body.email,password:req.body.password}, (error,result)=>{
if(error){
res.status(500).send(error);
}else{
var token = jwt.sign({email:result[0].email,password:result[0].password},getSecret());
res.status(200).send(token);
}
})
})
register request inserts new user record and return token for login
router.post('/register',(req,res)=>{ var model = {
f_name:req.body.fname,
l_name:req.body.lname,
email:req.body.email,
password:req.body.password
} UserSchema.insertMany(model,(error,result)=>{
if(error){
res.status(500).send(error);
}else{
var token = jwt.sign({email:result[0].email,id:result[0]._id},getSecret());
res.status(200).send(token);
}
})
})
access is simple request example for verify user before access resources
we need to add new function to authfunctions file for verify user and we need to import it.
function VerifyUser(token){
//User Verification Code
var stt = null;
jwt.verify(token,getSecret(),function (error,decode){
if(error){
stt = {
status : false,
error : error.message
}
}else{
stt = {
status : true,
decode : decode
}
}
})
return stt;
}//modify export code
module.exports = {VerifyUser,getSecret}
then access file
//modify import code also
const {getSecret,VerifyUser} = require('../functions/AuthFunctions');router.get('/access',(req,res)=>{
var token = req.headers.authorization.split(" ")[1];
var statusi = VerifyUser(token);
//this function can use to access authentication resources
res.send(statusi);
})
thsis is end of authentication using jwt note. thank you…