Generate JWT token after login and verify with Node.js API

Generate JWT token after login and verify with Node.js API

Generate JWT token after login and verify with Node.js API

In my last tutorial, I explained about how to login and register the user in the Node.js without using any security token.

But now I will tell you how to create a token using JWT library and authenticate APIs using the generated token in Node.js application.

Authentication, is what? It is just the way to keep unauthorized users out from accessing your secure APIs to interact with the database. Authentication is a main concern of the secure application.

Token based authentication is called stateless and session less because whenever we authenticate any user then we do not save any user details on the server, We simply generate a token that is signed by a private key and send it to the user to authenticate all secure api with generated token.

In this post, The flow of authenticate a token is as follows :

  • Verify username and password from the database.
  • Generate a JWT token if user credentials match with database record and send it to the client.
  • The client saves token and sends it with all secure APIs.
  • Use middleware to verifies the token and process the request.

You can send token in any way but this is good practice to send token in an HTTP header.

Getting Started

Before going with the steps, Make sure you have installed node and npm.

Let's have a look at our directory structure for Node application.

Directory Structure

  1. ├── controllers
  2. │ └── authenticate-controller.js
  3. ├── node_modules
  4. ├── config.js
  5. ├── index.js
  6. └── package.json
Require the dependencies for Node Application

package.json is a beginning file for node application where you can see the list installed packages in your node application.

package.json
{
  "name": "jwt",
  "version": "1.0.0",
  "description": "jwt authentication",
  "main": "index.js",
  "dependencies": {
    "body-parser": "^1.17.1",
    "express": "^4.14.1",
    "jsonwebtoken": "^7.3.0",
    "mysql": "^2.13.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

express module is the very popular Node framework.

body-parser module is used to get data from POST request.

jsonwebtoken module is used to generate and authenticate our JSON Web Tokens.

mysql module is how you work with database.

Configure database connection

In this step, we will create a connection object that will used with every database query.

config.js
  1. var mysql = require('mysql');
  2. var connection = mysql.createConnection({
  3. host : 'localhost',
  4. user : 'root',
  5. password : '',
  6. database : 'test'
  7. });
  8. connection.connect(function(err){
  9. if(!err) {
  10. console.log("Database is connected");
  11. } else {
  12. console.log("Error while connecting with database");
  13. }
  14. });
  15. module.exports = connection;
Node Application : index.js

In this step, we will include the packages we installed.

  1. var express=require("express");
  2. var bodyParser=require('body-parser');
  3. var jwt= require("jsonwebtoken");
  4. var app = express();
  5. var router=express.Router();
  6. var authenticateController=require('./controllers/authenticate-controller');
  7. process.env.SECRET_KEY="thisismysecretkey";
  8. app.use(bodyParser.urlencoded({extended:true}));
  9. app.use(bodyParser.json());
  10. app.post('/api/authenticate',authenticateController.authenticate);
  11. app.use('/secure-api',router);
  12. // validation middleware
  13. router.use(function(req,res,next){
  14.     var token=req.body.token || req.headers['token'];
  15.     if(token){
  16.         jwt.verify(token,process.env.SECRET_KEY,function(err,ress){
  17.             if(err){
  18.                 res.status(500).send('Token Invalid');
  19.             }else{
  20.                 next();
  21.             }
  22.         })
  23.     }else{
  24.         res.send('Please send a token')
  25.     }
  26. })
  27. router.get('/home',function(req,res){
  28.     res.send('Token Verified')
  29. })
  30. app.listen(8012);

In above code, i use middleware to protect last API prefix with 'secure-api' (localhost:8012/secure-api/home).

Create Authenticate Controller to generate token

In above code, I have defined a route to handle post request from the url localhost:8012/api/authenticate and respectively I have called authenticate method which is defined into authenticate controller.

So let's create a authenticate-controller.js, Where we validate user details and then generate a token.

controllers/authenticate-controller.js
  1. var jwt=require('jsonwebtoken');
  2. var connection = require('./../config');
  3. module.exports.authenticate=function(req,res){
  4.     var email=req.body.email;
  5.     var password=req.body.password;
  6.     connection.query('SELECT * FROM users WHERE email = ?',[email], function (error, results, fields) {
  7.      if (error) {
  8.          res.json({
  9.             status:false,
  10.             message:'there are some error with query'
  11.             })
  12.      }else{
  13.      if(results.length >0){
  14.          if(password==results[0].password){
  15.              var token=jwt.sign(results[0],process.env.SECRET_KEY,{
  16.                     expiresIn:5000
  17.                 });
  18.                 res.json({
  19.                     status:true,
  20.                     token:token
  21.                 })
  22.          }else{
  23.              res.json({
  24.                  status:false,        
  25.          message:"Email and password does not match"
  26.          });
  27.          }
  28.     
  29.      }
  30.      else{
  31.      res.json({
  32.          status:false,
  33.      message:"Email does not exits"
  34. });
  35.      }
  36.      }
  37.     });
  38. }

Now start the server by running following command :

node index.js
Test Our API to Authenticate User and Create a Token with Postman

Generate token using JWT

Test Our API to Authenticate token

First, i will hit api localhost:8012/secure-api/home without sending any token to test our middleware.

Invalid token

Now let's send the token with request.

Vefiry token with JWT

Phone: (+91) 8800417876
Noida, 201301
ataşehir escort maltepe escort bostancı escort kadıköy escort maltepe escort ataşehir escort tuzla escort pendik escort ümraniye escort kartal escort
pendik escort
izmir escort izmir escort izmir escort izmir escort denizli escort antalya escort antalya escort antalya escort izmir escort izmir escort izmir escort izmir escort izmir escort