πŸ” 3.7 Authentication & Authorization β€” Securing Your Node.js App Like a Pro

Table of Contents

Hey little coder! πŸ‘‹

Ever wondered how websites like Facebook know who you are? Or how some users can access admin stuff, and others can’t?

That’s where Authentication and Authorization come in.
Let’s break them down and build a secure Node.js app together πŸš€


🧠 What is Authentication vs Authorization?

πŸ‘€ Authentication = “Who are you?”

You log in with your email and password. The system checks if you’re really you.

Like a security guard checking your ID πŸͺͺ

πŸ” Authorization = “What can you do?”

Once you’re in, what are you allowed to do? View pages? Edit users? Access admin panel?

Like getting a wristband at a concert 🎟️ β€” red for VIP, blue for regular.


πŸ”§ Tools We’ll Use

ToolPurpose
bcryptjsHash passwords
jsonwebtokenCreate and verify JWTs
expressCreate server and APIs
middlewareSecure routes and check permissions

πŸ› οΈ Step-by-Step: Secure a Node.js App (With JWT + bcrypt)

We’ll build a simple system:

  • Register new users
  • Login users with JWT
  • Protect private routes
  • Restrict access by role (admin vs user)

βš™οΈ 1. Set Up Your Project

bashCopyEditmkdir auth-app
cd auth-app
npm init -y
npm install express bcryptjs jsonwebtoken dotenv

Folder Structure (Simple Version):

bashCopyEditauth-app/
β”œβ”€β”€ index.js
β”œβ”€β”€ .env
β”œβ”€β”€ users.js
└── middleware/
    └── auth.js

πŸ“ 2. Create a Simple User Store (Without DB For Now)

jsCopyEdit// users.js
const users = [];

module.exports = users;

We’ll simulate a database with an array for now πŸ“¦


πŸ” 3. Register a New User

βœ… Steps:

  1. Hash the password with bcryptjs
  2. Save the user to our store
jsCopyEdit// index.js
const express = require('express');
const bcrypt = require('bcryptjs');
const users = require('./users');

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

app.post('/register', async (req, res) => {
  const { email, password, role } = req.body;
  const hashedPassword = await bcrypt.hash(password, 10);
  
  users.push({ email, password: hashedPassword, role: role || "user" });
  res.status(201).json({ message: "βœ… User registered!" });
});

πŸ”“ 4. User Login and JWT Token Creation

jsCopyEditconst jwt = require('jsonwebtoken');
require('dotenv').config();

app.post('/login', async (req, res) => {
  const { email, password } = req.body;
  const user = users.find(u => u.email === email);

  if (!user) return res.status(400).json({ message: "User not found" });

  const valid = await bcrypt.compare(password, user.password);
  if (!valid) return res.status(401).json({ message: "Invalid credentials" });

  const token = jwt.sign({ email: user.email, role: user.role }, process.env.JWT_SECRET, { expiresIn: '1h' });
  res.json({ token });
});

πŸ—οΈ .env file should contain:

iniCopyEditJWT_SECRET=supersecretkey

πŸ”’ 5. Middleware to Protect Routes

jsCopyEdit// middleware/auth.js
const jwt = require('jsonwebtoken');

function authMiddleware(req, res, next) {
  const authHeader = req.headers['authorization'];
  const token = authHeader?.split(' ')[1];

  if (!token) return res.sendStatus(401);

  jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
    if (err) return res.sendStatus(403);
    req.user = user;
    next();
  });
}

module.exports = authMiddleware;

πŸšͺ 6. Create a Protected Route

jsCopyEditconst auth = require('./middleware/auth');

app.get('/profile', auth, (req, res) => {
  res.json({ message: `Welcome ${req.user.email}!`, role: req.user.role });
});

πŸ§ͺ Send a request with the token in header:

makefileCopyEditAuthorization: Bearer <token>

πŸ§™β€β™‚οΈ 7. Role-Based Access Control

Let’s only allow admins to access certain routes:

jsCopyEditfunction adminOnly(req, res, next) {
  if (req.user.role !== 'admin') return res.sendStatus(403);
  next();
}

app.get('/admin', auth, adminOnly, (req, res) => {
  res.json({ message: "Welcome Admin! πŸ‘‘" });
});

πŸ” This checks the user’s role from the JWT payload.


🎨 Infographic Placeholder

Title: JWT Authentication Flow (Visual)

 Diagram Showing Login β†’ Jwt β†’ Protected Routes β†’ Role Checks
πŸ” 3.7 Authentication & Authorization β€” Securing Your Node.js App Like A Pro 2

πŸ“‹ Recap – What We Learned

βœ… What authentication and authorization mean
βœ… How to hash passwords with bcrypt
βœ… How JWT helps us create secure sessions
βœ… Middleware to protect routes
βœ… Role-based access to limit actions


πŸ’¬ Real-World Tips

  • 🧯 Always store passwords hashed (never plain!)
  • πŸ›‘οΈ Keep your JWT_SECRET safe and private
  • ♻️ Use token expiration to force re-login after some time
  • 🚫 Never expose sensitive info inside JWT

πŸ”” Ready to Build Real Projects?

Try building a:

  • πŸ§‘β€πŸŽ“ Student dashboard with roles: admin, teacher, student
  • πŸ›’ E-commerce site with buyer and seller dashboards
  • ✍️ Blog with author/editor permissions

🧩 Coming Up in Part 2?

If you’d like, I can show:

  • How to store users in MongoDB or PostgreSQL
  • Use refresh tokens for longer sessions
  • Logout and token invalidation

🧑 Support & Learn With Us

If you learned something today, help us grow:

πŸ“Ί Subscribe to Web Codder on YouTube
πŸ“Έ Follow us on Instagram
πŸ’¬ Join our WhatsApp community

Let’s make the web safer, together πŸ’ͺπŸ”

Share the Post:
Picture of Web Codder

Web Codder

Vikas Sankhla is a seasoned Full Stack Developer with over 7 years of experience in web development. He is the founder of Web Codder, a platform dedicated to providing comprehensive web development tutorials and resources. Vikas specializes in the MERN stack (MongoDB, Express.js, React.js, Node.js) and has been instrumental in mentoring aspiring developers through his online courses and content. His commitment to simplifying complex web technologies has made him a respected figure in the developer community.

Related Posts