SecuritySecuring JSON APIs: Threats and Mitigations
A focused look at securing APIs that use JSON for data exchange.
Securing JSON APIs: Common Threats and How to Mitigate Them
JSON APIs are the backbone of modern web and mobile applications. They're also a prime target for attackers. This guide covers the most common JSON API security threats and concrete steps you can take to defend against them.
1. JSON Injection
The threat: If you build JSON strings by concatenating user input, an attacker can inject malicious JSON that alters your data structure.
Bad (vulnerable):
const body = `{"username": "${req.body.username}"}`;
// Attacker sends: alice", "admin": true
// Result: {"username": "alice", "admin": true}
Fix: Always use JSON.stringify() or your framework's built-in serialization — never string concatenation.
const body = JSON.stringify({ username: req.body.username }); // Safe
2. Excessive Data Exposure
The threat: Your API returns entire database objects (including sensitive fields like passwords, tokens, internal IDs) and lets the client filter what to display. If the client is compromised or the request is intercepted, all that data is exposed.
Fix: Create API-specific response DTOs (Data Transfer Objects) that only include the fields the client actually needs. Never serialize your entire database model directly.
// Bad: returns entire user object including passwordHash, internalId
res.json(user);
// Good: explicit allowlist of safe fields
res.json({ id: user.id, name: user.name, email: user.email });
3. Missing or Weak Input Validation
The threat: Unvalidated JSON input can contain unexpected types, oversized payloads, or missing required fields — causing crashes or unexpected behaviour.
Fix: Use a JSON Schema validator (like AJV in Node.js) to validate every incoming payload before processing it.
import Ajv from 'ajv';
const ajv = new Ajv();
const schema = {
type: 'object',
properties: {
email: { type: 'string', format: 'email' },
age: { type: 'integer', minimum: 0, maximum: 150 }
},
required: ['email'],
additionalProperties: false // Block unexpected fields
};
const validate = ajv.compile(schema);
if (!validate(req.body)) {
return res.status(400).json({ errors: validate.errors });
}
Note the additionalProperties: false — this prevents clients from injecting extra fields you don't expect.
4. Mass Assignment Attacks
The threat: Attackers send extra JSON fields (like isAdmin: true) hoping your server blindly assigns them to your model.
Fix: Use an explicit allowlist when applying request data to your model. Never use Object.assign(user, req.body) directly.
// Dangerous: assigns any field the client sends
Object.assign(user, req.body);
// Safe: only update specific allowed fields
user.name = req.body.name;
user.email = req.body.email;
5. Denial of Service via Large Payloads
The threat: An attacker sends a huge JSON payload (e.g., 1GB) causing your server to exhaust memory during parsing.
Fix: Set a payload size limit in your web framework.
// Express.js
app.use(express.json({ limit: '100kb' }));
Also protect against deeply nested JSON that causes stack overflows during recursive parsing.
6. Insecure JWT Handling
JSON Web Tokens (JWTs) are widely used for API authentication. Common mistakes:
- Using
alg: none(allows token forgery) - Not validating the
exp(expiry) claim - Storing the JWT secret in code or
.envfiles committed to git
Fix:
// Always specify allowed algorithms explicitly
jwt.verify(token, secret, { algorithms: ['HS256'] }, callback);
Security Checklist
- Validate all JSON input with a schema validator
- Use
additionalProperties: falsein your schemas - Never build JSON by string concatenation
- Set request body size limits
- Use explicit DTO/allowlist when reading user data into models
- Set
Content-Type: application/jsonon all API responses - Validate JWT
alg,exp, andissclaims - Use HTTPS everywhere — never send JSON over plain HTTP
- Rate-limit your endpoints
Security in JSON APIs isn't one big fix — it's a collection of small, consistent habits applied at every layer: input validation, serialization, authentication, and transport security.