Intermediate LevelREST APIs & Web Services
How do DTOs (Data Transfer Objects) and strict property whitelisting prevent Mass Assignment?
❓ Interview Prompt: Explain Mass Assignment vulnerability, ORM auto-binding dangers, DTOs, and field whitelisting.
Mass Assignment occurs when an API endpoint automatically binds unvalidated client JSON parameters directly to internal ORM database model properties:
Attack Scenario:
A user submits 'PUT /api/v1/profile' with body '{ "bio": "Hello", "role": "superadmin", "isVerified": true }'. If the backend uses 'User.update(req.body)', the attacker elevates privileges!
Defense:
Never pass raw 'req.body' to ORM models. Parse incoming data through explicit Data Transfer Objects (DTOs) or pick allowed keys using strict schema whitelisting.
Code Implementation Example
typescript
import pick from 'lodash/pick';
app.put('/api/v1/profile', async (req, res) => {
// ❌ Dangerous Mass Assignment: db.user.update(req.body);
// ✅ Safe Whitelisting using explicit DTO properties:
const safePayload = pick(req.body, ['firstName', 'lastName', 'bio']);
const updatedUser = await db.user.update({
where: { id: req.user.id },
data: safePayload
});
res.json(updatedUser);
});💡Preventing Mass Assignment using explicit DTO property picking.
🎯 Interview Key Takeaway
Use typed DTOs and strict property whitelisting to prevent attackers from injecting admin or payment fields via Mass Assignment.
#Mass Assignment#Security#DTO#Intermediate
Back to all REST APIs & Web Services Questions→