nodejs authentication with json web tokens (jwt) and postman tutorial

Spread the love

Nodejs authentication with JWT

JSON web tokens or JWT is a way of transferring data securely among servers. In a previous article, you have learned how to create a NodeJS HTTPS server and NodeJS REST API. In this nodejs authentication tutorial, you are going to create a restful API with JWT authentication.

Following tasks are performed in this tutorial.

1. Create a NodeJS, Express application

2. Install Nodemon, JSON web token(JWT) and Express modules

3. Create an API to secure with a JWT token

4. Test secured API routes with postman extension

nodejs authentication with jwt

Install NodeJS

In order to create nodejs authentication with JWT application, you need to install nodejs first. Visit NodeJS website and download. Install NodeJS. After installation, open command line, and type

/> node -v

You will see nodejs installed version.

Create a NodeJS application

NPM or node package manager is also installed with NodeJS installation. NPM is used to install and manage different node modules.

Open command line. Go to the directory where you want to create the nodejs application. Create a directory named – “nodejs-authentication-with-JWT“. Type command.

npm init

A wizard runs with different options. Select the default options. A nodejs application is generated.

Nodejs authentication with jwt

Install nodemon module

Nodemon module automatically restarts a nodejs application if any change is made to the code. Otherwise, you have to restart the application manually.

npm install --save-dev nodemon

Install JWT module

This module is an implementation of JSON web tokens used for secure communications.

npm install jsonwebtoken

Install Express module

Install Express module. Express is a minimalist framework for NodeJS.

npm install express

Start nodemon module

Open command line, go to project directory, type command

nodemon

NodeJS authentication in index.js file

Open index.js in your favorite IDE like Atom, Sublime Text or Visual Studio Code.

const express = require('express');

const jwt = require('jsonwebtoken');

const app = express();

The code above includes the express and JSON web token.

Create a signin route

In index.js create a route for user login. User authentication using database is not performed. This route returns a JWT token using jwt.sign method. The user object, app secret and an expiration time are passed to this method. This anonymous method gets a token and this token is sent back to the user browser using res.json(token).

//User signin route - create a token and return to user
app.post('/api/signin', (req, res) => {
    const user = {
        id: 1,
        username: "johndoe",
        email: "john.doe@test.com"
    }
    jwt.sign({user},'SuperSecRetKey', { expiresIn: 60 * 60 }, (err, token) => {
        res.json({token});
    });
});

Test routes using Postman

For testing protected nodejs authentication API, Postman Chrome extension is used.

Install Chrome Postman Extension

Open the Google Chrome browser, click on more tools >> extensions. Type postman. Install the extension.

Get JWT token using signin method

Open postman and add URL http://localhost:4000/api/signin and select the POST in methods drop down. Click Send button. You can see, a token is returned by the server. Copy this token. Token will be used with secure methods.

node authentication jwt get token

 

Verify Token method

Verify token method is added to authenticate token. This method accepts, req, res and next parameters. The request header’s authorization key contains token and is assigned to a constant bearerHeader.

Format of the authorization key

Authorization token has a format as bearer <authorizatin_key>. Split the string with space. Token is assigned to a constant bearerHeader. Assign token to req.token. next() middleware method is called. If the header is undefined then a 403 status is returned to the client.

/** verifyToken method - this method verifies token */
function verifyToken(req, res, next){
    
    //Request header with authorization key
    const bearerHeader = req.headers['authorization'];
    
    //Check if there is  a header
    if(typeof bearerHeader !== 'undefined'){

        const bearer = bearerHeader.split(' ');
        
        //Get Token arrray by spliting
        const bearerToken = bearer[1];

        req.token = bearerToken;

        //call next middleware
        next();

    }else{

        res.sendStatus(403);

    }
}

NodeJS authentication with JWT API Routes

In Chrome postman, type the URL http://localhost:4400/api. Select GET from methods drop-down and click Send button. You will see a welcome message

/* Creae API route */
app.get('/api', (req, res) => {
    res.json({

        msg: "Welcome to NodeJS JWT Authentication Tutorial"

    });

});

 

nodejs authentication with jwt

Create a Post with protected route

To create a post, the user needs to be authenticated first. A token is sent to post create route. In Postman, add URL http://localhpst:4400/api/posts. Select POST method in drop down. In params add the key as authorization. In values, tab add the word bearer and space. After space, add the token.

Pass verifyToken method as the second argument. In jwt.verify method accepts a token from req.token and same secret key. In the callback method err, and authData parameters are passed. If there is an error, status 403 is sent back. Otherwise, a new post is created and the message with authData is sent to the client.

/** Create posts protected route */

app.post('/api/posts', verifyToken, (req, res) => {

    jwt.verify(req.token, 'SuperSecRetKey', (err, authData)=>{

        if(err){

            res.sendStatus(403);

        }else{

            res.json({

                msg: "A new post is created",

                authData

            });
        }

    });

});

The image below shows an authorization key added in headers.

node authentication with jwt - post created with token

 

403 forbidden message

If we set an expiration time for the token and send a request after expiration time a forbidden message is sent to the client

node authentication with jwt - post created with token expiration

 

node authentication with jwt - post created with token forbidden

Create a nodejs server

Using app listen’s method a server is created. This server listens on port 4400 with a message on the console.

app.listen(4400, () => console.log(' Server started and listening on port: 4400'));

Summary

In the article, you have learned to install nodejs and create a nodejs express application. Next, nodejs modules are installed. Routes are created for a signin and API. A protected route is created to add a new post, with nodejs authentication.

You can download the JWT source code of this article from GitHub. To stay updated on upcoming articles. Follow us on twitter, like our facebook page or subscribe to our newsletter.

Related Articles:

 

Previous Article:

 

Next Article: