Node.js Authentication & Authorization (JWT, OAuth) | asadmukhtar.info
Step-by-Step Guide to Setting Up Authentication in Laravel 12 with Breeze   |   Manual Authentication in Laravel 12: Step-by-Step Guide   |   How to Build a REST API in Laravel 12 with Sanctum   |   Laravel 12 CRUD Application with Image Upload   |   Laravel 12 Multi-Auth System: Admin & User Login   |   How to Integrate Stripe Payment Gateway in Laravel 12   |   Building a Role-Based Access Control (RBAC) in Laravel 12   |   How to Use Laravel 12 Queues and Jobs for Background Tasks   |   Laravel 12 Livewire CRUD Example with Validation   |   Email Verification and Password Reset in Laravel 12   |   How to Use Laravel 12 API with Vue.js 3   |   Laravel 12 AJAX CRUD with jQuery and Bootstrap   |   Laravel 12 Multi-Language Website Setup   |   React Best Practices for 2025: Performance, SEO, and Scalability   |   How to Build a Full-Stack MERN App: A Step-by-Step Guide   |   React State Management: Redux vs. Context API vs. Recoil   |   Server-Side Rendering (SSR) in React with Next.js for SEO   |   How to Optimize React Apps for Faster Load Times   |   Building a REST API with Node.js and Express for a React App   |   Integrating JWT Authentication in React and Node.js (MERN Stack)   |   Real-time Chat App with React, Node.js, and Socket.io   |   How to Deploy a MERN Stack Application on AWS or Vercel   |   Connecting React Frontend to a Node.js Backend with Axios   |   Laravel Implement Flash Messages Example   |   How to integrate Angular 19 with Node.js and Express for full-stack development   |   Best practices for connecting Angular 19 frontend with Laravel API   |   Step-by-step guide to upgrading an existing project to Angular 19   |   How to implement authentication in Angular 19 using JWT and Firebase   |   Optimizing server-side rendering in Angular 19 with route-level render modes   |   Using Angular 19 signals for state management in large applications   |   How to create standalone components in Angular 19 for modular architecture   |   Building a CRUD application in Angular 19 with MongoDB and Express   |   Implementing lazy loading in Angular 19 to improve performance   |   How to integrate Angular 19 with GraphQL for efficient data fetching   |   Vue 3 Composition API vs Options API: A Comprehensive Comparison   |   Fetching and Displaying Data from APIs in Vue.js with Axios   |   Building a Todo App in Vue.js with Local Storage Integration   |   Handling Forms and Validation in Vue.js Using VeeValidate   |   State Management in Vue.js Applications Using Vuex   |   10 Most Important Tasks Every MERN Stack Developer Should Master   |   How to Build a Full-Stack CRUD App with MERN Stack   |   Best Practices for Authentication & Authorization in MERN Stack   |   1. MEAN Stack vs. MERN Stack: Which One Should You Choose in 2025   |   Top 10 Node.js Best Practices for Scalable and Secure Applications   |   How to Build a REST API with Laravel and Node.js (Step-by-Step Guide)   |   Mastering Angular and Express.js for Full-Stack Web Development   |   Top 10 Daily Tasks Every Frontend Developer Should Practice   |   Essential Backend Development Tasks to Boost Your Coding Skills   |   Real-World Mini Projects for Practicing React.js Daily   |   Laravel Developer Task List: Beginner to Advanced Challenges   |   How to Assign Effective Tasks to Your Intern Developers   |   10 Must-Try Tasks to Master JavaScript Fundamentals   |   Practical CSS Challenges That Improve Your UI Design Skills   |   Top Tasks to Learn API Integration in React and Angular   |   Best Task Ideas for a 30-Day Web Development Challenge   |   Top Git and GitHub Tasks Every Developer Should Know   |   30-Day Task Plan for Web Development Interns   |   Weekly Task Schedule for Junior Developers in a Startup   |   How to Track Progress with Development Tasks for Interns   |   What Tasks Should You Give to Interns in a MERN Stack Project   |   Build These 5 Projects to Master React Routing   |   Task-Based Learning: Become a Full-Stack Developer in 90 Days   |   Daily Coding Tasks That Will Sharpen Your Logical Thinking   |   Top 7 Backend Task Ideas to Practice With Node.js and MongoDB   |  

Step 1: Setting Up Your Node.js Project

Before we begin, ensure that you have Node.js and npm installed on your machine. If not, download and install Node.js from the official website.

  1. Verify installation:

node -v
npm -v

Create a new Node.js project:

mkdir my-auth-project
cd my-auth-project
npm init -y

Install necessary dependencies

npm install express jsonwebtoken passport passport-jwt oauth2-server

Step 2: Implementing JWT Authentication in Node.js

JWT is a popular method for handling authentication in modern web applications. It allows you to securely transmit user data between the client and the server as a signed token.

  1. Install JWT library:

npm install jsonwebtoken

Create a simple Express server:

const express = require('express');
const jwt = require('jsonwebtoken');

const app = express();
const PORT = 3000;

app.use(express.json());

// Secret key for signing JWT
const secretKey = 'yourSecretKey';

// Login route - generates JWT on successful login
app.post('/login', (req, res) => {
  const { username, password } = req.body;

  // Simple check (In real applications, authenticate from a DB)
  if (username === 'user' && password === 'password') {
    const token = jwt.sign({ username }, secretKey, { expiresIn: '1h' });
    return res.json({ token });
  }
  return res.status(401).json({ message: 'Invalid credentials' });
});

// Protected route - requires a valid JWT
app.get('/protected', (req, res) => {
  const token = req.headers['authorization']?.split(' ')[1];
  if (!token) return res.status(403).json({ message: 'Token is required' });

  jwt.verify(token, secretKey, (err, decoded) => {
    if (err) return res.status(401).json({ message: 'Invalid token' });
    return res.json({ message: 'Welcome to the protected route!', user: decoded });
  });
});

app.listen(PORT, () => console.log(`Server running on http://localhost:${PORT}`));
  1. Test the JWT:

    • First, send a POST request to /login with username user and password password to get the JWT.
    • Then, use the token to access the /protected route by passing the token in the Authorization header.

Step 3: Implementing OAuth Authentication in Node.js

OAuth is a widely used authorization framework that allows third-party services to access user data without sharing login credentials. OAuth provides a secure and scalable way to authenticate users using popular services like Google, Facebook, etc.

  1. Install OAuth2 library:

npm install oauth2-server

Set up OAuth2 Server:

const express = require('express');
const OAuth2Server = require('oauth2-server');
const app = express();
const oauth = new OAuth2Server({
  model: require('./model'), // OAuth model handling the data
  accessTokenLifetime: 3600,
  allowBearerTokensInQueryString: true,
});

// Middleware to authenticate using OAuth2
app.all('/oauth/token', oauth.token());

app.listen(3000, () => {
  console.log('OAuth server listening on port 3000');
});

OAuth Model: The model in OAuth handles data such as clients, access tokens, and authorization codes. Here's an example structure for the OAuth model:

module.exports = {
  getAccessToken: function (token) {
    return { accessToken: token, client: { id: 'clientId' }, user: { id: 'userId' } };
  },
  saveToken: function (token, client, user) {
    return { ...token, client, user };
  },
  getClient: function (clientId, clientSecret) {
    return { id: clientId, secret: clientSecret };
  },
  getUser: function (username, password) {
    return { id: 'userId', username };
  }
};
  1. Test OAuth2: Use tools like Postman to test OAuth2 endpoints by requesting an access token and using it to access protected resources.

Conclusion:

Implementing authentication and authorization in Node.js applications is essential for protecting user data and controlling access to resources. In this guide, we explored two common approaches: JWT and OAuth.

  • JWT is ideal for applications where you need stateless authentication, where tokens are issued upon successful login and used for subsequent requests.
  • OAuth is best for scenarios where you need third-party service integrations, allowing users to authenticate with services like Google, Facebook, or GitHub.

Both methods are highly secure, but they serve different purposes. While JWT works well for simpler use cases and single-service applications, OAuth is more suited for complex, distributed systems requiring third-party service integration.

Pros and Cons:

Pros:

  • JWT: Simple to implement, stateless, easy to scale.
  • OAuth: Secure, allows third-party integration, widely supported.

Cons:

  • JWT: Tokens can become large, and if not managed properly, can lead to security risks such as token theft.
  • OAuth: More complex to implement, requires setting up external services and handling scopes and permissions.

In conclusion, understanding the difference between JWT and OAuth will help you choose the right authentication and authorization strategy for your Node.js application, depending on your specific needs. Both offer excellent security features, but each has its strengths in different contexts.