Skip to main content
login bootstrap ui

User Authentication using JWT (JSON Web Token) with Node.js

I have already shared tutorials to authenticate user using MySQL with express, that was a simple authentication process using session, but nowadays front-end and back-end use a different application, so we have two layers one front-end and second for back-end, both applications is communication using restful service, so the main question is how to identify the user is authenticated(Real user) in a stateless application.

As like the above scenario, The JWT (JSON Web Token) has come into the picture that is used to protect API endpoints, and is often issued using OpenID Connect.

A JWT token string is a signed certificate using public/private key pairs. In this tutorial, I will create nodejs application to authenticate user using JWT and the second part of this tutorial will contain information on how to use JWT in angularjs application or communicate with client(angularjs) application and a server application(node js).

Updated: You can read Part2- Angularjs user authetication with JWT nodejs

Once the user is logged in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.

I will use following Node js modules into this application

  • express : This is a web framework for node
  • cors : This is use for CROSS origin functionality
  • body-parser : Node.js body parsing middleware
  • doenv : To manage .env file into application
  • jsonwebtoken : JSON Web Token is use to encode useful information and stored into string token.

There are following files will participate into this application

  • app.js : This is main node js entry file
  • package.json : Package dependency file.
  • routes/user.js : This is main file to handle all login, registration and validate user method.

Checkout Other NodeJS tutorials,

How to handle environment variable into Nodejs

We will use dotenv node module to handle environment variable into application, we will include dotenv dependency into package.json file and installed it, We can use inject module into app.js file as like below,
require('dotenv').config();

we will create .env file into root of nodejs application and add MySQL environment variable,

DB_HOST=localhost 
DB_NAME =test_login
DB_USER =root 
DB_PASS=''

So now we defined and access above variable like below,

var connection = mysql.createConnection({
	host: process.env.DB_HOST,
	user: process.env.DB_USER,
	password: process.env.DB_PASS,
	database : process.env.DB_NAME
});

Main benefit of .env file is, no one can see your config variable/credentials unless you shared,This is very helpful if your project is hosted on global repository like github etc.


Step 1: Create package.json file and paste below code this file.

{
  "name": "login_backend",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node app.js"
  },
  "dependencies": {
     "express": "4.8.7",
      "jsonwebtoken": "^7.4.1",
    "ejs": "*",
     "body-parser": "^1.16.1",
    "cors": "^2.8.3",
    "dotenv": "^4.0.0",
    "mysql": "^2.13.0"
  }
}

Now we have defined all dependencies of node modules into above file, now run npm install command , that will install all modules into node_modules/ folder.

Step 2: Create app.js file and paste below code this file.

/**
 * Module dependencies.
 */
require('dotenv').config();
var express = require('express') 
  , user = require('./routes/user')
  , http = require('http')
  , path = require('path');
var cors = require('cors');
var app = express();
var bodyParser=require("body-parser");
var jwt = require('jsonwebtoken');
var mysql    = require('mysql');
var connection = mysql.createConnection({
		host: process.env.DB_HOST,
		user: process.env.DB_USER,
		password: process.env.DB_PASS,
		database : process.env.DB_NAME
	});


connection.connect(function(err) {
  if(err)
	console.log(err);
});

global.db = connection;

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(function(req, res, next) {
	  res.header("Access-Control-Allow-Origin", "*");
	  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
	  next();
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

I have instantiated and included all node modules and configured MySQL with this.

Step 3: Created user.js file and added dependency into top of the file.

var jwt = require('jsonwebtoken');
var atob = require('atob');
var Cryptr = require('cryptr'),
cryptr = new Cryptr('myTotalySecretKey');

User Registration using Node js and Express

Step 1: Added routes login rest call into app.js file.
app.post('/signup', user.signup);

The rest end point is '/signup', that will call user file signup method.

Step 2: We will define signup() method into users.js file and paste the below code.

exports.signup=function(req , res){
	 var fname  = req.body.first_name;
	 var lname= req.body.last_name;
	 var pass= req.body.password;
	 var email=req.body.email;
	 var dec_pass =atob(pass);
	 var encrypted_pass = cryptr.encrypt(dec_pass);

	 var sql = "INSERT INTO `login`(`id`,`first_name`,`last_name`,`email`,`password`) VALUES ('','" + fname + "','" + lname + "','" +email+ "','" +encrypted_pass+ "')";
	  	var query = db.query(sql, function(err, result){
		
	  		res.end(JSON.stringify(result));
	});

};

Authenticate of Node.js API with JSON Web Tokens

Step 1: Added routes login rest call into app.js file.
app.post('/signin', user.signin);

The rest end point is '/signin', that will call user file signin method.

Step 2: We will define signin() method into users.js file, first i ll create user.js file and paste below code.

	
	var name=req.body.email;
 	var pass= req.body.password;
 	var dec_pass =atob(pass);
	var encrypted_pass = cryptr.encrypt(dec_pass);
	
	 var sql="SELECT id, first_name, last_name, email FROM `login` WHERE `email`='"+name+"' and password = '"+encrypted_pass+"'";
	 
	 db.query(sql, function(err, results){	
		 
		 if(results != ""){
			 
			 console.log(JSON.stringify(results));
			 
			 var data = JSON.stringify(results);
			 
			 var secret = 'TOPSECRETTTTT';
				var now = Math.floor(Date.now() / 1000),
					iat = (now - 10),
					expiresIn = 3600,
					expr = (now + expiresIn),
					notBefore = (now - 10),
					jwtId = Math.random().toString(36).substring(7);
				var payload = {
					iat: iat,
					jwtid : jwtId,
					audience : 'TEST',
					data : data
				};	
				
			 
			 jwt.sign(payload, secret, { algorithm: 'HS256', expiresIn : expiresIn}, function(err, token) {
					
				if(err){
					console.log('Error occurred while generating token');
					console.log(err);
					return false;
				}
				 else{
				if(token != false){
					//res.send(token);
					res.header();
					res.json({
  						"results":
  								{"status": "true"},
  						"token" : token,
						"data" : results
										
  					});
					res.end();
				}
				else{
					res.send("Could not create token");
					res.end();
				}
				
				 }
			});
		
		 }
		 else if(results == ""){
			 	console.log("not a user");
		 }
	 });
};

So as you can see in nodejs user registration functionality, We have stored the password into the MySQL database as an encrypted, so I will encrypt the user password and match it with a user registered password string, if the password is matched then returned token with in response object otherwise failed message.

You can download the source code from the below link.

4 thoughts to “User Authentication using JWT (JSON Web Token) with Node.js”

  1. If you read the .readme file for cryptr it actually states “**DO NOT USE THIS MODULE FOR ENCRYPTING PASSWORDS!**”

Leave a Reply

Your email address will not be published. Required fields are marked *