Authentication and Authorization in Node.js with JWT

For users to safely log in and access resources without revealing personal information, any online application needs to be secure. The JSON Web Token (JWT) is one of the most popular ways to manage authentication and permission in Node.js. JWT offers a condensed, standalone technique for safely sending data as a JSON object between parties.

This blog will discuss:

  • The meaning of authorization and authentication.
  • Why JWT is so popular.
  • How to set up authentication in a Node.js application using JWT.
  • JWT security best practices.

Authentication vs Authorization

Let’s define the distinction between authorization and authentication before moving on to implementation:

  • Authentication, such as using a username and password to log in, confirms the identity of the user.
  • After authentication, authorization controls the user’s access (e.g., allowing an admin user to remove records).
  • JWT facilitates the effective management of both procedures in web applications.ations.

Why Use JWT for Authentication?

JWT is a popular authentication mechanism because:

  • Stateless – No need to store session data on the server.
  • Compact and Secure – Uses a signed token to transmit user data.
  • Easy to Implement – Works well with RESTful APIs.
  • Cross-Domain Support – Works across different platforms (mobile, web, backend services).

How JWT Works in Node.js

  1. The user logs in with their credentials.
  2. If valid, the server generates a JWT and sends it to the client.
  3. The client includes the token in the headers of future requests.
  4. The server verifies the token and grants or denies access to resources.

Setting Up JWT Authentication in Node.js

Let’s implement JWT authentication using Express.js and jsonwebtoken.

Step 1: Install Dependencies

Ensure you have Node.js installed, then run:

npm init -y  # Initialize a new project
npm install express jsonwebtoken bcryptjs dotenv
  • express: Web framework for Node.js.
  • jsonwebtoken: For generating and verifying JWTs.
  • bcryptjs: For hashing passwords.
  • dotenv: For environment variables.

Step 2: Create a Basic Express Server

Create server.js and set up an Express app:

const express = require("express");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");
const dotenv = require("dotenv");

dotenv.config();
const app = express();
app.use(express.json());

const users = []; // In-memory user storage (replace with DB in production)

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

Step 3: User Registration

Hash the user’s password before storing it:

app.post("/register", async (req, res) => {
  const { username, password } = req.body;
  const hashedPassword = await bcrypt.hash(password, 10);
  users.push({ username, password: hashedPassword });
  res.status(201).json({ message: "User registered successfully" });
});

Step 4: User Login & Token Generation

Validate user credentials and issue a JWT:

app.post("/login", async (req, res) => {
  const { username, password } = req.body;
  const user = users.find(u => u.username === username);
  if (!user || !(await bcrypt.compare(password, user.password))) {
    return res.status(401).json({ message: "Invalid credentials" });
  }
  const token = jwt.sign({ username: user.username }, process.env.JWT_SECRET, { expiresIn: "1h" });
  res.json({ token });
});

Step 5: Protect Routes with JWT Middleware

Create a middleware to verify JWT tokens:

const authenticateToken = (req, res, next) => {
  const token = req.header("Authorization");
  if (!token) return res.status(403).json({ message: "Access denied" });
  
  jwt.verify(token.split(" ")[1], process.env.JWT_SECRET, (err, user) => {
    if (err) return res.status(403).json({ message: "Invalid token" });
    req.user = user;
    next();
  });
};

Step 6: Create a Protected Route

Only authenticated users can access this:

app.get("/protected", authenticateToken, (req, res) => {
  res.json({ message: "Welcome to the protected route, " + req.user.username });
});

Best Practices for JWT Security

  • Use Effective Secrets Keep your JWT_SECRET in a.env file and use a strong key.
  • Set Token Expiry: Short-lived tokens (expiresIn: “1h”) reduce the likelihood of misuse.
  • Use HTTPS: Secure connections prevent the interception of tokens.
  • Consider keeping revoked tokens in a database when you’re logging out.
  • Use Refresh Tokens: Provide users with persistent refresh tokens to reauthenticate them.

In conclusion

JWT is a useful technique for integrating authentication and permission in Node.js applications. By following suggested procedures, you may preserve system security while preserving a seamless user experience..

How Backend Development Powers Modern Web Applications

Which Framework Should I Learn in 2025?

₹25,000.00

SAP SD S4 HANA

SAP SD (Sales and Distribution) is a module in the SAP ERP (Enterprise Resource Planning) system that handles all aspects of sales and distribution processes. S4 HANA is the latest version of SAP’s ERP suite, built on the SAP HANA in-memory database platform. It provides real-time data processing capabilities, improved…
₹25,000.00

SAP HR HCM

SAP Human Capital Management (SAP HCM)  is an important module in SAP. It is also known as SAP Human Resource Management System (SAP HRMS) or SAP Human Resource (HR). SAP HR software allows you to automate record-keeping processes. It is an ideal framework for the HR department to take advantage…
₹25,000.00

Salesforce Administrator Training

I am text block. Click edit button to change this text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.
₹25,000.00

Salesforce Developer Training

Salesforce Developer Training Overview Salesforce Developer training advances your skills and knowledge in building custom applications on the Salesforce platform using the programming capabilities of Apex code and the Visualforce UI framework. It covers all the fundamentals of application development through real-time projects and utilizes cases to help you clear…
₹25,000.00

SAP EWM

SAP EWM stands for Extended Warehouse Management. It is a best-of-breed WMS Warehouse Management System product offered by SAP. It was first released in 2007 as a part of SAP SCM meaning Supply Chain Management suite, but in subsequent releases, it was offered as a stand-alone product. The latest version…
₹25,000.00

Oracle PL-SQL Training Program

Oracle PL-SQL is actually the number one database. The demand in market is growing equally with the value of the database. It has become necessary for the Oracle PL-SQL certification to get the right job. eLearning Solutions is one of the renowned institutes for Oracle PL-SQL in Pune. We believe…
₹25,000.00

Pega Training Courses in Pune- Get Certified Now

Course details for Pega Training in Pune Elearning solution is the best PEGA training institute in Pune. PEGA is one of the Business Process Management tool (BPM), its development is based on Java and OOP concepts. The PAGA technology is mainly used to improve business purposes and cost reduction. PEGA…
₹27,000.00

SAP PP (Production Planning) Training Institute

SAP PP Training Institute in Pune SAP PP training (Production Planning) is one of the largest functional modules in SAP. This module mainly deals with the production process like capacity planning, Master production scheduling, Material requirement planning shop floor, etc. The PP module of SAP takes care of the Master…
X
WhatsApp WhatsApp us
Call Now Button