🔐 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