DEV Community

Cover image for Unlocking the Power of JSON Web Tokens: Demystifying Authorization and Authentication in Node.js
Adolph Odhiambo
Adolph Odhiambo

Posted on

Unlocking the Power of JSON Web Tokens: Demystifying Authorization and Authentication in Node.js

In the vast digital landscape of today's interconnected applications, ensuring secure access and protecting user data are of paramount importance. As developers, we need reliable tools to handle authorization and authentication effectively. Enter JSON Web Tokens (JWTs), a compact and self-contained way to securely transmit information between parties as a JSON object. In the realm of Node.js, JWTs have emerged as a popular choice for implementing authorization and authentication mechanisms. In this blog post, we will dive into the world of JWTs, exploring their inner workings and uncovering how they can bolster the security of your Node.js applications. So fasten your seatbelts and get ready to embark on a journey where we unravel the secrets behind JWT-based authorization and authentication in Node.js.

What is jwt ??

At its core, a JWT is a string comprised of three distinct parts: the header, the payload, and the signature. The header contains information about the type of token and the algorithm used to sign it. The payload carries the claims or assertions about the user, such as their identity and any additional metadata. Finally, the signature ensures the integrity and authenticity of the token, preventing tampering and unauthorized modifications.

One of the significant advantages of JWTs is their self-contained nature, meaning all the necessary information is embedded within the token itself. This characteristic eliminates the need for server-side storage or database lookups, reducing the overall complexity and improving scalability. Additionally, the compact size of JWTs makes them ideal for transmitting across networks and storing within cookies or local storage.

When it comes to authentication, JWTs offer a reliable way to verify the identity of a user. Once a user provides their credentials, such as a username and password, the server can generate a JWT and send it back to the client. This token can then be included in subsequent requests, allowing the server to validate the user's identity without needing to store session data or perform database queries.

Authorization, on the other hand, deals with determining what actions a user is allowed to perform within an application. JWTs can carry additional claims in the payload, such as user roles or permissions, which can be utilized by the server to grant or deny access to certain resources or functionalities. By decoding the JWT and examining its payload, the server can make informed decisions about what the user is authorized to do.

NUFF said let's get our hands dirt !!!!

For this tutorial I am going to use Node js and following the MVC pattern a popular software architectural pattern.

Prerequisites

  • Installed Nodejs
  • Installed MongoDb
  • Code Editor

Here is my tree structure
Folders tree structure

1.Initializing the npm, run the following in the terminal

npm init -y

  1. Install the required dependencies:

npm install express axios mongoose bcryptjs cookie-parser cors dotenv hbs jsonwebtoken

  1. In the root folder create a folder with the name src inside the src folder create another folder called db we will use the db folder to store the database configurations . I will be using mongoDb
  • Create a file inside db and name it mongoose.js which looks like this
const mongoose = require("mongoose");
mongoose.set('strictQuery', false);

function connection() {
    mongoose.connect("mongodb://127.0.0.1:27017/authSec");
}

module.exports = { connection };

Enter fullscreen mode Exit fullscreen mode

The code above begins by importing the mongoose library, which is a popular Object-Document Mapping (ODM) library for MongoDB in Node.js. This library simplifies the interaction with MongoDB by providing a higher-level API and data modeling capabilities.

The line mongoose.set('strictQuery', false); sets the strictQuery option to false. This option allows more flexibility when querying the database, as it disables the strict mode for queries. In strict mode, Mongoose throws an error if you try to query with undefined fields. Setting it to false allows querying with undefined fields without throwing an error.

The connection function is defined, which is exported as a module. It handles establishing a connection to the MongoDB database. The mongoose.connect method is used to connect to the database specified by the MongoDB connection string mongodb://127.0.0.1:27017/authSec. Modify the connection string as per your MongoDB setup.

Finally, the connection function is exported using module.exports, allowing other parts of the application to import and utilize this function to establish a connection with the MongoDB database.

To use this code, you would typically import the connection function from this module and call it whenever you need to establish a connection with your MongoDB database.

  1. After initializing our database let's move to the server .Inside the src folder create two files server.js and app.js.
  2. We will have the following code inside the server.js.
const http = require("http");

const app = require("./app");

const PORT = process.env.PORT || 3000;

const server = http.createServer(app);
const { connection } = require("./db/mongoose");

server.listen(PORT, async() => {
    // console.log(`server has started on ${PORT}`)

    await connection();
    console.log(`server is listening on port ${PORT}`
    );
});
Enter fullscreen mode Exit fullscreen mode
  • The code begins by importing the http module, which is a built-in Node.js module that provides functionality for creating HTTP servers.

  • The app module is imported using require("./app"). This refers to a separate file that defines an Express application, which handles the routing and middleware logic for the server. We will create this file later

  • The PORT constant is defined, which specifies the port number on which the server will listen. It is set to the value of the process.env.PORT environment variable, which allows the server to use the port specified by the hosting environment. If the environment variable is not set, it defaults to port 3000.

  • The http.createServer(app) method is used to create an HTTP server instance, passing the app module as the request handler. This associates the Express application with the server, allowing it to handle incoming HTTP requests.

  • The connection function is imported from the "./db/mongoose" module. This likely refers to a separate file that establishes a connection to a MongoDB database using Mongoose.

Top comments (0)