Module 4: Web Application Security
Master OWASP Top 10, secure coding practices, and web vulnerability prevention.
OWASP Top 10
The Open Web Application Security Project (OWASP) Top 10 lists the most critical web application security risks. Every developer must know these!
1. SQL Injection
Attackers insert malicious SQL code to access or modify database data.
❌ Vulnerable Code:
const query = `SELECT * FROM users
WHERE email = '${email}'`;
// Attacker input:
// ' OR '1'=' 1 --
✅ Secure Code:
const query = 'SELECT * FROM users
WHERE email = $1';
db.query(query, [email]);
// Parameterized query
2. Cross-Site Scripting (XSS)
Injecting malicious scripts into web pages viewed by other users.
Types of XSS:
- Stored XSS: Script saved in database, affects all users
- Reflected XSS: Script in URL, affects clicked users
- DOM-based XSS: Client-side script manipulation
❌ Vulnerable:
<div>{userInput} </div>
✅ Secure:
<div>
{escapeHtml(userInput)}
</div>
3. Cross-Site Request Forgery (CSRF)
Tricks users into performing unwanted actions while authenticated.
CSRF Protection:
// Generate CSRF token
const csrfToken = crypto.randomBytes(32).toString('hex');
req.session.csrfToken = csrfToken;
// Include in form
<input type=\"hidden\" name=\"csrf\" value=\"${csrfToken}\" />
// Verify on submission
if (req.body.csrf !== req.session.csrfToken) {
throw new Error('Invalid CSRF token');
}
4. Broken Authentication
Weak authentication allows attackers to compromise accounts.
❌ Weak:
- • Weak password requirements
- • No rate limiting
- • Predictable session IDs
- • No MFA
- • Exposed credentials in URLs
✅ Strong:
- • Strong password policy
- • Rate limiting/account lockout
- • Secure session management
- • Multi-factor authentication
- • Secure password reset
5. Broken Access Control
Users can access resources they shouldn't have permission to.
Access Control Example:
app.get('/api/user/:id', async (req, res) => {
// Check if user can access this resource
if (req.user.id !== req.params.id && !req.user.isAdmin) {
return res.status(403).json({ error: 'Forbidden' });
}
const user = await db.users.findById(req.params.id);
res.json(user);
});
API Security Best Practices
Authentication
Use JWT, OAuth 2.0, or API keys. Never trust client input.
Rate Limiting
Prevent abuse with request limits per user/IP.
Input Validation
Validate all inputs on server-side. Never trust client.
HTTPS Only
Always use TLS. Set HSTS headers.
Error Handling
Don't expose stack traces or sensitive info in errors.
Security Headers
// Essential 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();
});
📚 Module Summary
You've mastered web application security:
- ✓ OWASP Top 10 vulnerabilities
- ✓ SQL injection prevention
- ✓ XSS and CSRF protection
- ✓ Authentication and authorization
- ✓ API security best practices
- ✓ Security headers
Next: Learn penetration testing techniques!