Chapter 11: Security Patterns
Chapter 11 of 15
Chapter 11: Security Patterns
11.1 Security Best Practices
Security is critical for web applications. Implement comprehensive security measures to protect data and users.
Input Validation:
- Validate all user input on server-side
- Use whitelist approach (allow only known good)
- Sanitize data before processing
- Check data types and formats
- Enforce length limits
// Input validation example
const validator = require('validator');
function validateUserInput(data) {
const errors = [];
if (!validator.isEmail(data.email)) {
errors.push('Invalid email format');
}
if (!validator.isLength(data.name, { min: 2, max: 50 })) {
errors.push('Name must be 2-50 characters');
}
if (!validator.isAlphanumeric(data.username)) {
errors.push('Username must be alphanumeric');
}
return errors;
}
SQL Injection Prevention:
- Use parameterized queries (prepared statements)
- Never concatenate user input into SQL
- Use ORMs that handle escaping
- Validate and sanitize input
// BAD: SQL injection vulnerable
const query = `SELECT * FROM users WHERE email = '${email}'`;
// GOOD: Parameterized query
const query = 'SELECT * FROM users WHERE email = ?';
db.query(query, [email]);
// ORM automatically handles it
const user = await User.findOne({ where: { email } });
XSS (Cross-Site Scripting) Protection:
- Escape user input when displaying
- Use Content Security Policy (CSP)
- Sanitize HTML input
- Use framework's built-in escaping
// Escape output
const escaped = escapeHtml(userInput);
// Or use template engines that auto-escape
<%= user.name %> // Auto-escaped in EJS
CSRF (Cross-Site Request Forgery) Protection:
- Use CSRF tokens
- Validate tokens on state-changing requests
- Use SameSite cookie attribute
- Check Origin/Referer headers
11.2 Authentication Security
Secure authentication is fundamental to application security.
- Use strong password hashing (bcrypt, argon2)
- Implement password complexity requirements
- Use HTTPS for all authentication
- Implement account lockout after failed attempts
- Set secure cookie flags (HttpOnly, Secure, SameSite)
- Use short token expiration times
- Implement two-factor authentication (2FA)
11.3 Data Protection
Protect sensitive data throughout the application.
- Encrypt sensitive data at rest
- Use HTTPS for data in transit
- Don't log sensitive information
- Implement proper access controls
- Use environment variables for secrets
- Regular security audits
11.4 Security Headers
HTTP security headers provide additional protection.
// Security headers
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('X-XSS-Protection', '1; mode=block');
res.setHeader('Strict-Transport-Security', 'max-age=31536000');
res.setHeader('Content-Security-Policy', "default-src 'self'");
next();
});