API Security Best Practices
Security is critical for any API. Let's explore common vulnerabilities and how to prevent them.
OWASP API Security Top 10
1. Broken Object Level Authorization
Users access resources they shouldn't.
Bad:
// Anyone can access any user's data
app.get('/users/:id', (req, res) => {
const user = db.getUser(req.params.id);
res.json(user);
});
Good:
app.get('/users/:id', authenticate, (req, res) => {
// Check if user owns this resource
if (req.params.id !== req.user.id && !req.user.isAdmin) {
return res.status(403).json({ error: 'Forbidden' });
}
const user = db.getUser(req.params.id);
res.json(user);
});
2. Broken Authentication
Weak authentication mechanisms.
Prevent by:
- Use strong password requirements
- Implement account lockout
- Use secure token generation
- Enable MFA
3. Excessive Data Exposure
Returning more data than needed.
Bad:
// Returns password hash!
res.json(user);
Good:
res.json({
id: user.id,
name: user.name,
email: user.email
// password, salt, etc. NOT included
});
4. Lack of Rate Limiting
No protection against brute force.
Implement:
- Request rate limits
- Account lockout after failed attempts
- CAPTCHA for sensitive endpoints
5. Injection
SQL, NoSQL, command injection.
Bad:
const query = `SELECT * FROM users WHERE name = '${req.query.name}'`;
Good:
const query = 'SELECT * FROM users WHERE name = $1';
db.query(query, [req.query.name]);
Exercise: Security Checker
Loading JavaScript Exercise...
Input Validation
Always validate and sanitize input:
const { body, validationResult } = require('express-validator');
app.post('/users',
body('email').isEmail(),
body('password').isLength({ min: 8 }),
body('name').trim().escape(),
(req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Process valid input
}
);
Security Headers
Include security headers in responses:
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Strict-Transport-Security: max-age=31536000
Content-Security-Policy: default-src 'self'
Security Checklist
- Always use HTTPS
- Validate all input
- Use parameterized queries
- Implement proper authentication
- Check authorization for every request
- Rate limit sensitive endpoints
- Don't expose sensitive data
- Log security events
- Keep dependencies updated
- Regular security audits
Summary
API security requires:
- Strong authentication and authorization
- Input validation and sanitization
- Protection against injection attacks
- Rate limiting
- Minimal data exposure
- Security headers

