๐Ÿ” 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