Lesson 6 of 7By Taha Sufiyan
Last updated on Apr 9, 202118449Thousands of developers around the world use Node.js to develop I/O-intensive web applications, such as video streaming sites, single-page applications, online chat applications, and other web apps. The open-source (and completely free) platform offers several advantages over other server-side platforms, like Java or PHP.
This tutorial on Node.js authentication with JWT will help you learn how to add a security layer when accessing different routes within a Node.js web application. First, we will discuss the basics of JWT (JSON Web Token) and then cover its implementation within a Node.js application.
We will cover the following topics in this article:
JSON Web Token (JWT) is a standard that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. The compact size makes the tokens easy to transfer through an URL, POST parameter, or inside an HTTP header. The information in a JWT is digitally signed using a secret or public/private key pair.
JWTs can be signed using a secret or a public/private key pair.
JWTs are mainly used for authentication. After a user signs in to an application, the application then assigns JWT to that user. Subsequent requests by the user will include the assigned JWT. This token tells the server what routes, services, and resources the user is allowed to access.
Node.js authentication with JWT has several advantages over the traditional authentication process, primarily the scalability of stateless applications. And since it’s becoming popular among such heavyweights as Facebook and Google, it’s adoption across the industry likely will continue to grow.
Other advantages include:
There are several reasons why applications use JSON Web Tokens for authentication:
|
|
![]()
|
|
![]()
|
|
![]()
|
A JSON Web Token consists of:
Learn to build network applications quickly and efficiently using JavaScript with the Node.js Training. Click to enroll now!
Some scenarios where JSON Web Tokens are useful:
|
|
![]()
|
Next, we’ll look at some of the node applications using JWT.
The following application uses JWT authentication allowing users to access routes by logging in.
1. Download the Node.js. Select the installer according to your operating system and environment
2. Run the Node.js installer. Accept the license agreement. You can leave other settings as default. The installer will install Node.js and prompt you to click on the finish button.
3. Verify that Node.js was properly installed by opening the command prompt and typing this command: node --version
4. When we install Node.js, NPM (Node Package Manager) is also installed. NPM includes many libraries that are used in web applications, such as React. Verify whether it is installed with the following command in CMD: npm --version
Install a text editor of your choice. We are using Visual Studio Code in this tutorial, but you can use other editors, such as Atom or Sublime Text, if you are more comfortable with those.
We are using the Postman application to check the output of the application. We send and receive API calls and check if the JWT is working correctly.
To download the Postman application, go to its official website.
1. Create an empty folder and name it mongodb_crud.
2. Open the newly created directory in VS Code and (inside the terminal) type npm init to initialize the project. Press the Enter key to leave the default settings as they are.
We are going to create our own Node.js application and include JWT, thus adding a security mechanism to each route that we define in this application. This prevents unauthorized access and allows the logged in users to access the routes as long as they have the JWT token included in the header request.
Let’s first take a look at how the project directory should be at the end of this tutorial. We are working only on a single file called index.js, so the project directory is super simple.
Create a file called index.js in the project directory. This is the only file that we create and work on in this project in order to keep things simple. Our main goal is to understand how JWTs work in a Node.js application.
So, let’s go ahead and understand what each snippet of code does in this file.
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
app.get("/api", (req, res) => {
res.json({
message: "Hey, there! Welcome to this API service"
});
});
verify() method then takes the request token as input and verifies whether it is correct. We set it to print an error message if it doesn’t match; otherwise, we print a message on the screen stating that the post was created.
app.post("/api/posts", verifyToken, (req, res) => {
jwt.verify(req.token, "secretkey", (err, authData) => {
if (err) {
res.sendStatus(403);
} else {
res.json({
message: "POST created...",
authData
});
}
});
});
JWT then uses the sign() method to create a JSON Web Token for that user and returns the token in the form of a JSON string.
app.post("/api/login", (req, res) => {
const user = {
id: 1,
username: "john",
email: "john@gmail.com"
};
jwt.sign({ user: user }, "secretkey", (err, token) => {
res.json({
token
});
});
});
function verifyToken(req, res, next) {
const bearerHeader = req.headers["authorization"];
if (typeof bearerHeader !== "undefined") {
const bearerToken = bearerHeader.split(" ")[1];
req.token = bearerToken;
next();
} else {
res.sendStatus(403);
}
}
app.listen(3000, () => console.log("Server started"));
That’s all the code we are going to write to develop this application. Next, we’ll run the application by using the command node index.js in the terminal of the VS Code.
The terminal should look like this after using the above command:
If your terminal also displays Server started, it means that the server is running properly.
Now that you have learned about the value of Node.js authentication with JWT, you may be wondering how you can obtain the skills necessary to take advantage of its rising popularity. Fortunately, there are some great options to learn these skills at your own pace. Simplilearn’s Node.js Certification training course will give you a great, foundational understanding of this popular platform, combining live, instructor-led training, self-paced tutorials, and hands-on projects to help you become career-ready upon completion. Get started today and seize your future!
Taha is a Research Analyst at Simplilearn. He is passionate about building great user interfaces and keeps himself updated on the world of Artificial Intelligence. Taha is also interested in gaming and photography.
What is Node.js: A Comprehensive Guide
The Ultimate Tutorial to Getting Started With Node.js
Understanding Node.js Architecture
Top 48 Node.js Interview Questions and Answer
Node.js MySQL Tutorial: Create and Manage an Employee Database
Node.js Express Tutorial: Create a User Management System