MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Password Hashing with Bcrypt & Role-Based Access Control (RBAC)0%
Study Materials
Node.js & Express.jsProgress 0%
1.1Node.js Architecture, V8 Engine & Single-Threaded Event Loop1.2Call Stack, Callback Queue, Microtask Queue & Libuv Workers1.3Non-Blocking Asynchronous Code with Promises and Async/Await
5.1Input Validation & Data Sanitization with Joi or Zod5.2User Authentication with JWT (JSON Web Tokens) & HTTP-Only Cookies5.3Password Hashing with Bcrypt & Role-Based Access Control (RBAC)5.4Security Hardening: Helmet, CORS, Express Rate Limiting & HPP5.5Production Configuration, Environment Variables & PM2 Process Manager
HomeTutorialsNode.js & Express.jsPassword Hashing with Bcrypt & Role-Based Access Control (RBAC)
Security Hardening: Helmet, CORS, Express Rate Limiting & HPP

Password Hashing with Bcrypt & Role-Based Access Control (RBAC)

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

Storing plaintext passwords in a database is an egregious security violation. In this tutorial, we implement military-grade password hashing with Bcrypt and implement Role-Based Access Control (RBAC) to restrict sensitive endpoints based on user permissions.


1. Why Bcrypt? (Salting & Adaptive Work Factors)

MD5 and SHA-256 are designed to be fast, making them vulnerable to modern GPU brute-force attacks capable of testing billions of hashes per second.

Bcrypt counters this with two essential security features:

  1. 1
    Cryptographic Salt: Appends random bytes to the password before hashing, preventing Rainbow Table lookup attacks.
  2. 2
    Adaptive Work Factor (Cost Factor): Allows developers to slow down the algorithm exponentially. A cost factor of 12 means an attacker takes hundreds of milliseconds per guess on high-end hardware, making brute force economically impossible.
1import bcrypt from 'bcrypt';
2 
3const SALT_ROUNDS = 12;
4 
5// Hash password before saving to database
6export async function hashPassword(plainPassword) {
7 return await bcrypt.hash(plainPassword, SALT_ROUNDS);
8}
9 
10// Compare password during login
11export async function verifyPassword(plainPassword, storedHash) {
12 return await bcrypt.compare(plainPassword, storedHash);
13}

2. Role-Based Access Control (RBAC) Architecture

RBAC restricts resource access based on assigned organizational roles (e.g., student, instructor, admin, superadmin).

1Incoming Request -> [ Authenticate JWT ] -> [ RestrictTo('admin', 'instructor') ] -> [ Controller ]

Implementing the Authorization Guard:

1// src/middleware/authorize.js
2export const restrictTo = (...allowedRoles) => {
3 return (req, res, next) => {
4 // req.user was populated by prior authentication middleware
5 if (!req.user || !allowedRoles.includes(req.user.role)) {
6 return res.status(403).json({
7 status: 'fail',
8 message: `Forbidden: You do not have permission to perform this action. Required: [${allowedRoles.join(', ')}]`
9 });
10 }
11 next();
12 };
13};

3. Protecting Admin Endpoints

1import { Router } from 'express';
2import { protectRoute } from '../middleware/auth.middleware.js';
3import { restrictTo } from '../middleware/authorize.js';
4import * as userController from '../controllers/user.controller.js';
5 
6const router = Router();
7 
8// 1. Any logged-in user can view their own profile
9router.get('/me', protectRoute, userController.getMyProfile);
10 
11// 2. ONLY users with role 'admin' can delete other user accounts
12router.delete('/:id', protectRoute, restrictTo('admin'), userController.deleteUser);
13 
14// 3. Instructors or Admins can publish courses
15router.post('/courses', protectRoute, restrictTo('instructor', 'admin'), userController.createCourse);
16 
17export default router;

Interactive Quiz• Knowledge Check

Multiple Choice Questions

Question 1
Why are fast hashing algorithms like SHA-256 unsuitable for storing user passwords compared to Bcrypt?
Question 2
What is a "Salt" in password hashing?
Question 3
What does bcrypt.compare(candidatePassword, userHash) return?
Question 4
In Role-Based Access Control (RBAC), what HTTP status code indicates that the authenticated user lacks sufficient permissions for a requested resource?
Question 5
What is the recommended default salt work factor (cost) for Bcrypt in modern web applications?

Next Lesson

Security Hardening: Helmet, CORS, Express Rate Limiting & HPP

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
User Authentication with JWT (JSON Web Tokens) & HTTP-Only CookiesSecurity Hardening: Helmet, CORS, Express Rate Limiting & HPP

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master Node.js & Express.js with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext