The Security Guard at AQAD Headquarters
Imagine AQAD has grown into a massive company.
Inside the building are:
- Vendor Management Department
- Retailer Operations Department
- Finance Department
- Analytics Department
- Executive Offices
Sensitive information exists everywhere.
Examples:
- Product pricing
- Vendor contracts
- Retailer purchase history
- Payment records
- Sales analytics
Now imagine there is no security guard at the entrance.
Anyone could walk in. A stranger could enter the finance department.
Someone could access confidential reports.
Someone could modify business data. The company would quickly become a disaster.
This is why organizations verify identity before granting access.
Applications work exactly the same way.
Before allowing access, applications ask:
Who are you?
The process of verifying identity is called:
Authentication
What Is Authentication?
Authentication is the process of verifying that a user is who they claim to be.
In simple words:
Authentication = Identity Verification
The application checks:
Are you really this user?
Only after verification is access granted.
Authentication vs Login
Many beginners think these terms are identical.
They are related but not exactly the same.
Login
The act of submitting credentials.
Example:
Password
Authentication
The verification process.
Example:
Check Email
Check Password
Verify User
Authentication happens behind the scenes after login.
Real AQAD Example
Retailer enters:
Email:
retailer@aqad.com
Password:
********
AQAD backend verifies:
- User exists?
- Password correct?
- Account active?
- Account verified?
If everything passes:
Access granted.
Otherwise:
Access denied.
Why Authentication Exists
Without authentication,
every application would be vulnerable.
Imagine AQAD without login.
Anyone could:
- View orders
- Place orders
- Modify products
- Access analytics
- View payment records
That would be catastrophic.
Authentication protects systems from unauthorized access.
Everyday Authentication Examples
You already use authentication daily.
ATM Machine
Before accessing money:
Insert Card
Enter PIN
Identity verified.
Mobile Phone
Before unlocking:
PIN
Fingerprint
Face ID
Identity verified.
Email Account
Before opening inbox:
Password
Identity verified.
Applications follow the same principle.
Authentication Flow
Let's understand the complete process.
Step 1
User enters credentials.
Example:
Password
Step 2
Frontend sends request.
POST /login
Step 3
Backend receives request.
Step 4
Database searched.
Step 5
User found.
Step 6
Password verified.
Step 7
Authentication successful.
Step 8
Access granted.
AQAD Login Lifecycle
Retailer opens application.
↓
Enters credentials.
↓
Clicks Login.
↓
Request sent:
POST /login
↓
Backend receives request.
↓
Database verifies user.
↓
Password validated.
↓
Token generated.
↓
Response returned.
↓
Retailer enters dashboard.
This happens in seconds.
Traditional Username and Password Authentication
The oldest and most common authentication method.
User provides:
Username
Password
Example:
{
"email":"retailer@aqad.com",
"password":"123456"
}
Backend verifies credentials.
Simple.
Widely used.
Why Passwords Are Not Stored Directly
Here's something extremely important.
Professional applications never store plain passwords.
Bad example:
{
"email":"user@gmail.com",
"password":"123456"
}
Very dangerous.
If database is leaked,
every password becomes exposed.
The Locker Analogy
Imagine storing valuables.
Would you place them:
Open Table
or
Locked Safe
Obviously the safe.
Password hashing acts like a digital safe.
We'll cover hashing deeply later.
Authentication Factors
Security experts classify authentication methods into factors.
Something You Know
Examples:
Password
PIN
Security Questions
Something You Have
Examples:
Mobile Phone
OTP Device
Security Token
Something You Are
Examples:
Fingerprint
Face Recognition
Retina Scan
Modern systems often combine multiple factors.
Multi-Factor Authentication (MFA)
MFA means:
More than one verification method.
Example:
Step 1:
Password
Step 2:
OTP
Only after both are verified:
Access granted.
Real AQAD Example
Retailer logs in.
Password verified.
AQAD sends:
OTP: 456789
Retailer enters OTP.
Identity confirmed.
This greatly improves security.
Why MFA Is Important
Suppose attacker steals password.
Without MFA:
Account Compromised
With MFA:
Attacker still needs:
OTP Device
Much safer.
Session-Based Authentication
One traditional authentication approach.
Let's understand using a hotel analogy.
Hotel Wristband Analogy
Imagine checking into a resort.
Reception verifies identity.
Then gives:
Wristband
You don't repeatedly show ID.
The wristband identifies you.
Sessions work similarly.
Session Flow
User logs in.
↓
Server verifies credentials.
↓
Server creates session.
↓
Session ID generated.
↓
Browser stores session ID.
↓
Future requests use session ID.
Server remembers user information.
This is called:
Stateful Authentication
Session Example
User logs in.
Server creates:
{
"sessionId":"abc123"
}
Server stores:
{
"sessionId":"abc123",
"userId":1001
}
Future requests use that session.
Problems with Sessions
Sessions work well.
But large systems face challenges.
Example:
AQAD expands globally.
Servers:
Dubai
India
Europe
USA
Now every server must know session information.
Scaling becomes difficult.
This led to another solution:
Token-Based Authentication.
Token-Based Authentication
Instead of storing session information on the server,
the server gives the user a token.
Think of it as:
A temporary digital identity card.
Airport Boarding Pass Analogy
When you check into a flight:
Airport verifies identity.
Then gives:
Boarding Pass
Later:
You simply show the boarding pass.
No need to repeat passport verification everywhere.
Tokens work similarly.
Token Authentication Flow
User logs in.
↓
Credentials verified.
↓
Token generated.
↓
Token returned.
↓
Client stores token.
↓
Future requests send token.
↓
Server verifies token.
↓
Access granted.
AQAD Example
Login successful.
Response:
{
"token":"xyz123"
}
Future request:
Authorization: Bearer xyz123
Backend verifies token.
Access granted.
Authentication Middleware
Remember Chapter 7?
Middleware acts as a security guard.
Authentication middleware checks:
Valid User?
before route access.
Example Flow
Request:
GET /orders
↓
Authentication Middleware
↓
Token Verified
↓
Controller Executes
↓
Orders Returned
If verification fails:
401 Unauthorized
Request stops immediately.
Common Authentication Methods
Modern applications commonly use:
Email + Password
Most common.
OTP Authentication
Popular in mobile apps.
Social Login
Examples:
- Apple
MFA Authentication
Password + OTP
Biometric Authentication
Fingerprint and Face ID.
Authentication in AQAD
Possible login methods:
Vendor
Email + Password
Retailer
Email + Password
Employee
Email + Password + MFA
Admin
Email + Password + MFA
Higher privileges require stronger security.
Common Authentication Mistakes
Mistake 1
Storing plain passwords.
Never do this.
Mistake 2
Weak password policies.
Example:
123456
Mistake 3
Not implementing MFA for sensitive accounts.
Mistake 4
Returning sensitive information.
Example:
{
"password":"123456"
}
Mistake 5
Trusting client-side verification.
Always verify on the server.
Real AQAD Login Flow
Retailer enters:
Password
↓
Frontend sends request.
↓
Backend validates credentials.
↓
Database verifies user.
↓
Password verified.
↓
Token generated.
↓
Response:
{
"token":"abc123"
}
↓
Retailer accesses dashboard.
↓
Future requests include token.
↓
Authentication middleware verifies token.
↓
Protected resources become accessible.
Interview Questions
What is authentication?
Authentication is the process of verifying a user's identity.
Why is authentication important?
It prevents unauthorized access to systems and data.
Difference between authentication and authorization?
Authentication verifies identity.
Authorization verifies permissions.
What is MFA?
Multi-Factor Authentication uses multiple verification methods to improve security.
Why should passwords be hashed?
To protect passwords if the database is compromised.
Authorization Explained
Getting Into the Building Doesn't Mean You Can Enter Every Room
Let's continue with our AQAD headquarters example.
Imagine you arrive at the AQAD office.
At the entrance, the security guard checks your identity card.
Everything looks good.
You are verified.
The security guard says:
Welcome. You may enter.
Now imagine you immediately walk toward:
Finance Department
and attempt to open the door.
The system responds:
Access Denied
Why?
Because being identified is not enough.
The company must also determine:
What are you allowed to access?
This is where authorization begins.
Authentication vs Authorization
Many beginners confuse these concepts.
Understanding the difference is critical.
Authentication
Authentication answers:
Who are you?
Example:
I am John.
System verifies identity.
Access to the building granted.
Authorization
Authorization answers:
What are you allowed to do?
Example:
Can John access Finance?
System checks permissions.
Access may be granted or denied.
Easy Way to Remember
Authentication:
Identity Check
Authorization:
Permission Check
Real AQAD Example
Retailer logs in.
Authentication verifies:
Valid Retailer
Now retailer attempts:
DELETE /products/101
Should this be allowed?
No.
Deleting products belongs to vendors or administrators.
Authorization blocks the request.
Why Authorization Exists
Imagine AQAD without authorization.
Any user could:
- Delete products
- Modify inventory
- Access payment records
- View vendor contracts
- Access analytics
The platform would become unsafe immediately.
Authorization protects resources by enforcing permissions.
The Hotel Analogy
Imagine staying at a luxury hotel.
At check-in:
Your identity is verified.
Authentication complete.
You receive a room card.
Now try opening:
Another Guest's Room
Access denied.
Try opening:
Staff Room
Access denied.
Try opening:
Management Office
Access denied.
The card determines what areas you may access.
That is authorization.
Roles and Permissions
Most applications organize authorization using:
Roles
and
Permissions
Role
A role is a collection of permissions.
Examples:
Admin
Vendor
Retailer
Employee
Permission
A permission defines a specific action.
Examples:
Create Product
Delete Product
Create Order
View Analytics
Manage Users
AQAD Role Structure
Let's design a simple authorization system.
Vendor
Can:
Create Products
Update Products
Manage Inventory
View Orders
View Analytics
Cannot:
Delete Retailers
Manage Employees
View All Payments
Retailer
Can:
Browse Products
Place Orders
Track Orders
Manage Profile
Cannot:
Create Products
Modify Inventory
Delete Vendors
Logistics Partner
Can:
View Assigned Deliveries
Update Delivery Status
Manage Route Information
Cannot:
Create Products
Manage Vendors
View Finance Reports
Admin
Can:
Manage Everything
Highest privilege level.
Authorization Flow
Let's see how authorization works.
Step 1
User logs in.
Authentication successful.
Step 2
User requests resource.
Example:
DELETE /products/101
Step 3
Authorization middleware checks role.
Step 4
Permission evaluated.
Step 5
Access granted or denied.
Visual Flow
Request
↓
Authentication
↓
Authorization
↓
Controller
↓
Response
Notice:
Authorization happens after authentication.
Why?
Because we must know who the user is before checking permissions.
Authorization Middleware
Just like authentication middleware,
authorization middleware acts as a gatekeeper.
Example:
const authorizeVendor =
(req, res, next) => {
if (
req.user.role !== "vendor"
) {
return res
.status(403)
.json({
message:
"Access Denied"
});
}
next();
};
Understanding HTTP 403
Remember status codes?
Authorization failures typically return:
403 Forbidden
Meaning:
We know who you are.
But you cannot access this resource.
This is different from:
401 Unauthorized
Which means:
We do not know who you are.
Easy Memory Trick
401
Not Logged In
403
Logged In
But No Permission
Real AQAD Example
Retailer request:
DELETE /products/101
Authentication:
Retailer Verified
Authorization:
Retailers Cannot Delete Products
Response:
403 Forbidden
Request ends.
Role-Based Access Control (RBAC)
One of the most common authorization models.
RBAC stands for:
Role-Based Access Control
Instead of assigning permissions directly to users,
we assign permissions to roles.
Users inherit permissions through their role.
Why RBAC Is Popular
Imagine AQAD has:
50,000 Retailers
10,000 Vendors
500 Employees
20 Admins
Managing permissions individually would be impossible.
RBAC simplifies management.
RBAC Structure
Example:
Admin
Permissions:
Manage Users
Manage Products
Manage Orders
Manage Payments
Manage Analytics
Vendor
Permissions:
Create Product
Update Product
Manage Inventory
Retailer
Permissions:
Place Orders
View Orders
Track Deliveries
Users inherit permissions automatically.
Resource-Based Authorization
Sometimes permissions depend on ownership.
Example:
Vendor A owns:
Product 101
Vendor B owns:
Product 202
Vendor A should not modify Vendor B's product.
Even though both are vendors.
AQAD Ownership Example
Request:
PUT /products/202
Backend checks:
Is Vendor A the owner?
If no:
403 Forbidden
Access denied.
This is resource-level authorization.
Authorization Database Example
Many systems store permissions in tables.
Example:
Users:
| User ID | Role |
|---|---|
| 1 | Admin |
| 2 | Vendor |
| 3 | Retailer |
Permissions:
| Role | Permission |
|---|---|
| Admin | Delete Product |
| Vendor | Create Product |
| Retailer | Place Order |
Backend checks these mappings during requests.
AQAD Permission Architecture
Let's design something realistic.
Product Permissions
Vendor:
Create
Update
View
Admin:
Create
Update
Delete
View
Retailer:
View Only
Order Permissions
Retailer:
Create Order
View Own Orders
Vendor:
View Related Orders
Admin:
View All Orders
Analytics Permissions
Vendor:
Own Analytics
Admin:
Global Analytics
Authorization protects all these resources.
Why Authorization Must Be Server-Side
A dangerous beginner mistake:
Checking permissions only in the frontend.
Example:
if(user.role === "admin"){
showDeleteButton();
}
This improves user experience.
But it is not security.
Attackers can still call APIs directly.
Always enforce authorization on the backend.
Frontend vs Backend Authorization
Frontend:
Hide Buttons
Show Menus
Improve UX
Backend:
Real Security
Permission Enforcement
Backend authorization is mandatory.
Multiple Authorization Layers
Large applications often combine several checks.
Example:
Authentication
↓
Role Check
↓
Ownership Check
↓
Resource Access Check
Each layer improves security.
Real AQAD Product Update Flow
Vendor requests:
PUT /products/101
↓
Authentication Middleware
User Verified
↓
Authorization Middleware
Vendor Role Verified
↓
Ownership Verification
Product Belongs To Vendor
↓
Controller Executes
Product Updated
↓
Response
200 OK
This is how production systems operate.
Common Authorization Mistakes
Mistake 1
Confusing authentication with authorization.
Mistake 2
Checking permissions only in frontend.
Mistake 3
Giving users excessive permissions.
Mistake 4
Ignoring ownership checks.
Mistake 5
Using hardcoded role logic everywhere.
Principle of Least Privilege
A very important security principle.
Users should receive:
Only the permissions they need.
Not more.
Example:
Retailers should not receive:
Delete Product Permission
Because they don't need it.
This reduces security risks.
Real-World Applications of Authorization
Authorization exists everywhere.
Examples:
Banking Apps
Customers cannot access other customer accounts.
Social Media
Users cannot delete other users' posts.
Hospital Systems
Doctors access patient records.
Receptionists access appointment schedules.
Different permissions.
AQAD
Vendors, retailers, logistics partners, and admins all have different access levels.
Interview Questions
What is authorization?
Authorization determines what actions a user is allowed to perform.
Difference between authentication and authorization?
Authentication verifies identity.
Authorization verifies permissions.
What is RBAC?
Role-Based Access Control assigns permissions through roles.
What status code is commonly returned for authorization failures?
403 Forbidden
Why should authorization always be enforced on the backend?
Because frontend checks can be bypassed.
JWT Authentication
The Hotel Room Key Analogy
Imagine you check into a hotel.
At the reception desk:
- Your identity is verified
- Your booking is confirmed
- Your payment is checked
After verification, the receptionist gives you a room key.
Example:
Room 507 Key
Now think about what happens next.
Every time you:
- Enter your room
- Use the elevator
- Access hotel facilities
You don't go back to the reception desk and prove your identity again.
Instead, you simply show your room key.
The hotel trusts the key because it was issued by the hotel itself.
JWT works in a very similar way.
After login, the server gives the user a digital key.
That key is used for future requests.
This digital key is called:
JWT
What Is JWT?
JWT stands for:
JSON Web Token
It is a secure way to transmit user information between a client and a server.
In simple words:
JWT is a digital identity card issued after successful authentication.
Why JWT Was Created
Remember Chapter 9?
We discussed session-based authentication.
Sessions work well.
But large modern applications need something more scalable.
Consider AQAD.
Imagine:
50,000 Retailers
10,000 Vendors
500 Employees
If every server stores session information:
- Memory usage increases
- Scaling becomes difficult
- Synchronization becomes complicated
JWT solves these problems.
JWT Authentication Flow
Let's understand the complete lifecycle.
Step 1
User logs in.
Example:
{
"email":"retailer@aqad.com",
"password":"******"
}
Step 2
Backend verifies credentials.
Step 3
JWT token generated.
Step 4
Token sent to client.
Example:
{
"token":"eyJhbGciOi..."
}
Step 5
Client stores token.
Step 6
Future requests include token.
Authorization: Bearer TOKEN
Step 7
Backend verifies token.
Step 8
Access granted.
Real AQAD Example
Retailer logs in.
↓
Backend verifies credentials.
↓
JWT generated.
↓
Response:
{
"token":"abc123xyz"
}
↓
Retailer opens orders page.
↓
Request:
GET /orders
Authorization: Bearer abc123xyz
↓
Backend validates token.
↓
Orders returned.
Simple.
Fast.
Scalable.
Understanding JWT Structure
A JWT consists of three parts.
HEADER.PAYLOAD.SIGNATURE
Example:
xxxxx.yyyyy.zzzzz
Each section has a purpose.
Part 1: Header
Contains token metadata.
Example:
{
"alg":"HS256",
"typ":"JWT"
}
Meaning:
Algorithm Used
Token Type
Part 2: Payload
Contains user information.
Example:
{
"userId":1001,
"role":"retailer"
}
Payload stores claims about the user.
Part 3: Signature
The most important part.
Generated using:
Header
+
Payload
+
Secret Key
The signature prevents tampering.
Passport Analogy
Imagine a passport.
Passport contains:
- Name
- Nationality
- Passport Number
If someone changes information manually,
official verification fails.
JWT signatures work similarly.
If token data is modified:
Verification fails.
Access denied.
JWT Claims
Claims are pieces of information stored inside the payload.
Example:
{
"userId":1001,
"role":"vendor",
"email":"vendor@aqad.com"
}
Common claims:
User ID
Role
Permissions
Expiration Time
Important JWT Rule
JWT is not encryption.
Anyone can decode the payload.
Therefore:
Never store sensitive information.
Bad example:
{
"password":"123456"
}
Never do this.
Good JWT Payload Example
{
"userId":1001,
"role":"vendor"
}
Safe.
Minimal.
Professional.
Generating JWT in Node.js
Most Node.js applications use:
npm install jsonwebtoken
Package:
const jwt = require("jsonwebtoken");
Creating a Token
Example:
const token = jwt.sign(
{
userId: 1001,
role: "vendor"
},
"SECRET_KEY"
);
Token generated.
Understanding jwt.sign()
First argument:
{
userId:1001,
role:"vendor"
}
Payload.
Second argument:
"SECRET_KEY"
Secret used for signature generation.
Verifying JWT
When requests arrive:
Backend verifies token.
Example:
jwt.verify(
token,
"SECRET_KEY"
);
If valid:
Access granted.
If invalid:
Access denied.
Authentication Middleware with JWT
Remember middleware?
JWT fits perfectly.
Example
const authMiddleware =
(req, res, next) => {
const token =
req.headers.authorization;
if (!token) {
return res
.status(401)
.json({
message:
"Unauthorized"
});
}
try {
jwt.verify(
token,
"SECRET_KEY"
);
next();
} catch {
return res
.status(401)
.json({
message:
"Invalid Token"
});
}
};
This is one of the most common middleware patterns in Express applications.
Protecting Routes
Public route:
app.get(
"/products",
getProducts
);
Anyone can access.
Protected route:
app.get(
"/orders",
authMiddleware,
getOrders
);
Only authenticated users.
Request Flow with JWT
Request:
GET /orders
Authorization: Bearer TOKEN
↓
Authentication Middleware
↓
JWT Verified
↓
Controller Executes
↓
Orders Returned
This happens constantly in production systems.
Token Expiration
JWT tokens should not last forever.
Why?
Imagine a hotel room key that never expires.
Huge security risk.
JWT supports expiration times.
Example:
jwt.sign(
payload,
secret,
{
expiresIn:"1h"
}
);
Token valid for one hour.
Why Expiration Is Important
Suppose a token is stolen.
Without expiration:
Attacker Access Forever
With expiration:
Access Ends Automatically
Much safer.
Access Tokens
Most systems use:
Access Token
Short-lived token.
Example:
15 Minutes
30 Minutes
1 Hour
Used for API requests.
Refresh Tokens
What happens after expiration?
Should users log in repeatedly?
Poor user experience.
Instead:
Applications use refresh tokens.
Hotel Extension Analogy
Imagine your hotel stay ends tomorrow.
Instead of checking out and checking in again,
you visit reception.
Hotel extends your stay.
Refresh tokens work similarly.
Refresh Token Flow
Login:
↓
Access Token Created
↓
Refresh Token Created
↓
Access Token Expires
↓
Refresh Token Generates New Access Token
↓
User remains logged in
This improves usability.
Access Token vs Refresh Token
| Access Token | Refresh Token |
|---|---|
| Short Life | Long Life |
| Used Frequently | Used Occasionally |
| Access APIs | Generate New Tokens |
| Higher Exposure | Stored More Carefully |
Most modern applications use both.
AQAD JWT Architecture
Let's design a realistic flow.
Retailer Login:
POST /login
↓
Credentials Verified
↓
Generate:
Access Token
Refresh Token
↓
Store Refresh Token Securely
↓
Return Access Token
↓
Retailer Requests Orders
GET /orders
Authorization: Bearer TOKEN
↓
JWT Middleware
↓
Token Verified
↓
Orders Returned
This architecture scales very well.
Common JWT Mistakes
Mistake 1
Using weak secret keys.
Bad:
123456
Use strong secrets.
Mistake 2
Storing sensitive data in payload.
Mistake 3
Never expiring tokens.
Mistake 4
Not validating tokens.
Mistake 5
Trusting decoded tokens without verification.
Always verify signature.
JWT Security Best Practices
Use HTTPS
Prevent token interception.
Use Expiration
Never issue permanent tokens.
Keep Payload Small
Store only necessary information.
Protect Secret Keys
Store in:
.env
Secrets Manager
Never hardcode in production.
Verify Every Request
Never trust incoming tokens blindly.
Real AQAD Request Lifecycle
Retailer logs in.
↓
JWT Issued.
↓
Retailer requests:
GET /orders
↓
JWT Middleware Executes.
↓
Token Verified.
↓
Role Extracted.
↓
Authorization Middleware Executes.
↓
Orders Controller Executes.
↓
Database Queried.
↓
Orders Returned.
A real-world backend system depends heavily on this workflow.
JWT vs Session Authentication
| JWT | Session |
|---|---|
| Stateless | Stateful |
| Scales Easily | Harder to Scale |
| Stored Client Side | Stored Server Side |
| Popular for APIs | Popular for Traditional Apps |
| Mobile Friendly | Web Friendly |
Modern APIs commonly prefer JWT.
Interview Questions
What is JWT?
JWT is a JSON Web Token used for authentication and secure information exchange.
What are the three parts of JWT?
Header
Payload
Signature
Why is JWT popular?
Because it is stateless and scalable.
What is the difference between Access Token and Refresh Token?
Access tokens access APIs.
Refresh tokens generate new access tokens.
Should sensitive data be stored in JWT payload?
No.
Payloads can be decoded.
Password Hashing with bcrypt
The Notebook Under the Reception Desk
Imagine AQAD stores all user passwords in a notebook.
The notebook contains:
| User | Password |
|---|---|
| Vendor1 | 123456 |
| Retailer1 | password123 |
| Admin | admin123 |
One day someone steals the notebook.
What happens?
Immediately:
- Every account is compromised
- Admin access is compromised
- Vendor accounts are compromised
- Retailer accounts are compromised
The entire platform becomes vulnerable.
Unfortunately, many beginners unknowingly build systems exactly like this.
They store passwords directly inside databases.
Professional applications never do this.
Instead, they use:
Password Hashing
Why Passwords Should Never Be Stored Directly
Let's imagine a database leak.
Bad database example:
{
"email":"vendor@aqad.com",
"password":"123456"
}
If attackers gain database access:
They instantly know every password.
No effort required.
This is one of the worst security mistakes a developer can make.
What Is Hashing?
Hashing converts data into a fixed-length value.
Example:
Password:
123456
After hashing:
$2b$10$T8QK7...
The original password becomes unreadable.
The Paper Shredder Analogy
Imagine writing:
123456
on paper.
Then feeding it into a shredder.
The paper becomes tiny pieces.
You can verify it came from the original paper.
But reconstructing it becomes extremely difficult.
Hashing works similarly.
Important Property of Hashing
Hashing is:
One-Way
Meaning:
Password → Hash
is easy.
But:
Hash → Password
is practically impossible.
This makes hashing ideal for passwords.
What Happens During Registration?
Suppose a retailer signs up.
Password:
myRetailer123
Backend receives password.
Before storing:
Hash Password
Database stores:
{
"email":"retailer@aqad.com",
"password":"$2b$10$..."
}
The original password is never stored.
What Happens During Login?
Many beginners ask:
If the password isn't stored, how can login work?
Good question.
Let's see.
Login Flow
User enters:
myRetailer123
Backend hashes the entered password.
New hash generated.
Backend compares:
Generated Hash
with
Stored Hash
If they match:
Authentication successful.
Why Simple Hashing Is Not Enough
Imagine using a very simple hashing algorithm.
Example:
123456
always produces:
ABC123
Attackers know common passwords.
They create huge lookup tables.
These are called:
Rainbow Tables
Rainbow Table Analogy
Imagine a cheat sheet.
| Password | Hash |
|---|---|
| 123456 | ABC |
| password | XYZ |
| admin123 | QWE |
Attackers can compare hashes quickly.
This makes simple hashing dangerous.
Enter Salting
To solve this problem,
developers use:
Salt
What Is Salt?
A salt is random data added to a password before hashing.
Example:
Password:
123456
Salt:
X7K92P
Combined:
123456X7K92P
Now hashing occurs.
Why Salt Is Important
Without salt:
Two users with the same password:
123456
produce identical hashes.
With salt:
Each user gets a unique hash.
Even when passwords are identical.
Real AQAD Example
Vendor:
Password: 123456
Hash:
Hash A
Retailer:
Password: 123456
Hash:
Hash B
Same password.
Different hashes.
Much safer.
What Is bcrypt?
bcrypt is one of the most popular password hashing libraries.
Node.js developers use it extensively.
Why?
Because bcrypt automatically handles:
- Hashing
- Salting
- Security complexity
Making password storage much safer.
Installing bcrypt
Install package:
npm install bcrypt
Import:
const bcrypt =
require("bcrypt");
Ready to use.
Hashing a Password
Example:
const password =
"myPassword123";
const hashedPassword =
await bcrypt.hash(
password,
10
);
Output:
$2b$10$...
Store this value in the database.
Understanding the Number 10
Example:
bcrypt.hash(
password,
10
)
The number:
10
represents:
Salt Rounds
Think of it as security strength.
Higher value:
More Secure
But Slower
Common production values:
10
12
14
AQAD Registration Example
Retailer registers.
Request:
{
"email":"retailer@aqad.com",
"password":"Retailer123"
}
Backend:
const hashedPassword =
await bcrypt.hash(
password,
10
);
Database stores:
{
"email":"retailer@aqad.com",
"password":"$2b$10$..."
}
Original password discarded.
Verifying Passwords
During login:
User enters:
Retailer123
Backend retrieves stored hash.
Now compare.
Example:
const isValid =
await bcrypt.compare(
password,
hashedPassword
);
Result:
true
or
false
Why compare() Is Important
Many beginners try:
password === hash
This will never work.
bcrypt hashes include:
- Salt
- Metadata
Always use:
bcrypt.compare()
Registration Lifecycle
User registers.
↓
Password received.
↓
bcrypt.hash()
↓
Hash generated.
↓
Database stores hash.
↓
User created.
Secure.
Professional.
Login Lifecycle
User enters password.
↓
Database retrieves stored hash.
↓
bcrypt.compare()
↓
Match?
If yes:
Authentication Successful
If no:
Invalid Credentials
Hashing vs Encryption
Many beginners confuse these concepts.
Let's clarify.
Hashing
One-Way
Cannot be reversed.
Used for:
Passwords
Encryption
Two-Way
Can be decrypted.
Used for:
Sensitive Data
Payment Information
Private Documents
Easy Analogy
Hashing:
Paper Shredder
Cannot reconstruct easily.
Encryption:
Locked Box
Can unlock with a key.
Why Not Use Encryption for Passwords?
Because we never need the original password.
We only need verification.
Hashing is safer.
Therefore:
Passwords should be hashed.
Not encrypted.
Password Security Best Practices
Professional applications enforce strong password policies.
Minimum Length
Example:
8+ Characters
Uppercase Letters
Example:
Password123
Lowercase Letters
Example:
password123
Numbers
Example:
123
Special Characters
Example:
@
#
$
!
AQAD Password Policy
Recommended:
Minimum 8 Characters
Uppercase Required
Lowercase Required
Number Required
Special Character Required
Much safer.
Common Password Attacks
Understanding attacks helps understand security.
Brute Force Attack
Attacker tries:
123456
123457
123458
...
until successful.
Dictionary Attack
Uses common passwords.
Example:
password
admin
123456
qwerty
Credential Stuffing
Uses leaked passwords from other websites.
Very common.
How bcrypt Helps
bcrypt slows down attackers.
Each password verification takes time.
Making mass attacks far more difficult.
This is one reason bcrypt remains popular.
Real AQAD Secure Login Architecture
Registration:
↓
Password Received.
↓
bcrypt.hash()
↓
Store Hash.
↓
User Created.
Login:
↓
Password Entered.
↓
Retrieve Hash.
↓
bcrypt.compare()
↓
Success?
↓
Generate JWT.
↓
User Logged In.
This is how most production Node.js applications operate.
Common Beginner Mistakes
Mistake 1
Storing plain passwords.
Mistake 2
Using weak password policies.
Mistake 3
Comparing password strings directly.
Mistake 4
Using outdated hashing algorithms.
Mistake 5
Logging passwords in server logs.
Never log passwords.
Interview Questions
What is password hashing?
Password hashing converts passwords into unreadable fixed-length values for secure storage.
Why should passwords be hashed?
To protect user accounts if the database is compromised.
What is bcrypt?
A password hashing library that provides hashing and salting.
What is a salt?
Random data added to a password before hashing.
Difference between hashing and encryption?
Hashing is one-way.
Encryption is reversible.

0 Comments