API - Mass Assignment
Mass assignment happens when an API automatically takes all the data sent by the user and assigns it directly to a database model without filtering which fields are allowed.
This becomes dangerous because a malicious user can send extra fields that they should not have control over.
❌ Why is Mass Assignment Dangerous?
Because attackers can modify sensitive fields that were never meant to be changed — such as:
-
role(e.g., make themselves admin) -
isActive -
balance -
isPaid -
password -
isAdmin
Simple Example
Bad API Code (Vulnerable to mass assignment)
Imagine we have a User model:
// User model fields
{
name: String,
email: String,
role: String, // "user" or "admin"
isActive: Boolean
}
And the API endpoint:
// ❌ Dangerous
app.post('/users', async (req, res) => {
const user = await User.create(req.body); // ← mass assignment
res.send(user);
});
{
"name": "John",
"email": "john@example.com"
}
But an attacker could send:
{
"name": "Hacker",
"email": "hack@example.com",
"role": "admin",
"isActive": true
}
Since the API uses req.body directly, the attacker becomes an admin.
This is mass assignment vulnerability.
🎯 Summary (Super Easy)
| Concept | Meaning |
|---|---|
| Mass assignment | Automatically assigning all user input to a model |
| Why risky? | Users can change protected fields |
| How to fix? | Allow only specific fields (whitelisting) |
Comments
Post a Comment