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.

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.