OWASP Top 10 Explained with Practical Examples
Why the OWASP Top 10 Matters
Every web developer eventually faces the same problem: you build a feature, ship it, and then a security scan or a pen test reveals a vulnerability you didn't anticipate. The OWASP Top 10 is a list of the most critical web application security risks, maintained by the Open Worldwide Application Security Project. It's not a checklist to tick once; it's a lens to review your code continuously.
This article walks through each risk with a concrete example and a practical fix. The examples are simplified but reflect real patterns found in production code.
A01: Broken Access Control
Broken access control occurs when users can act outside their intended permissions. A classic case: an API endpoint that fetches a user's data by ID without verifying ownership.
// Vulnerable: any logged-in user can read any order
app.get('/api/orders/:id', (req, res) => {
const order = db.getOrder(req.params.id);
res.json(order);
});
Fix: Always enforce authorization at the server. Check that the authenticated user owns the resource.
app.get('/api/orders/:id', (req, res) => {
const order = db.getOrder(req.params.id);
if (!order || order.userId !== req.user.id) {
return res.status(404).end(); // or 403
}
res.json(order);
});
Also, deny by default. Use middleware to require authentication on all routes except public ones.
A02: Cryptographic Failures
This category covers failures related to cryptography, often leading to sensitive data exposure. Examples: storing passwords in plain text, using weak hashing algorithms like MD5, or transmitting data over HTTP.
Fix: Use strong, adaptive hashing for passwords (bcrypt, Argon2). Enforce HTTPS with HSTS. Encrypt sensitive data at rest.
// Node.js: hash a password with bcrypt
const bcrypt = require('bcrypt');
const hash = await bcrypt.hash(password, 12);
const match = await bcrypt.compare(password, hash);
A03: Injection
Injection flaws, such as SQL, NoSQL, OS, and LDAP injection, occur when untrusted data is sent to an interpreter as part of a command or query. The attacker's hostile data can trick the interpreter into executing unintended commands.
// Vulnerable: string concatenation in SQL
const query = "SELECT * FROM users WHERE email = '" + email + "'";
Fix: Use parameterized queries or prepared statements. Never concatenate user input into queries.
// Safe: parameterized query
const query = 'SELECT * FROM users WHERE email = $1';
const values = [email];
const result = await db.query(query, values);
For OS commands, avoid shell execution; use APIs that separate arguments from the command.
A04: Insecure Design
Insecure design is about missing or ineffective control design. It's not about implementation bugs but about flaws in the architecture. Example: a password recovery flow that uses a security question with a guessable answer.
Fix: Threat modeling during design. Use secure design patterns, limit resource consumption, and validate business logic.
A05: Security Misconfiguration
This is the most common issue: default accounts, unnecessary features enabled, verbose error messages leaking stack traces, missing security headers.
Fix: Harden your stack. Remove unused features, change default credentials, and set security headers.
// Express.js: set security headers with helmet
const helmet = require('helmet');
app.use(helmet());
Also, disable directory listing in your web server and ensure error pages don't reveal internal details.
A06: Vulnerable and Outdated Components
Using libraries with known vulnerabilities is like leaving a door unlocked. Attackers scan for outdated versions.
Fix: Regularly update dependencies. Use tools like npm audit, OWASP Dependency-Check, or Dependabot. Remove unused dependencies.
A07: Identification and Authentication Failures
Weak authentication allows attackers to compromise passwords, keys, or session tokens. Examples: allowing brute force, weak password policies, exposed session IDs in URLs.
Fix: Implement multi-factor authentication, enforce strong passwords, use secure session management (HttpOnly, Secure, SameSite cookies), and rate-limit login attempts.
A08: Software and Data Integrity Failures
This relates to code and infrastructure that doesn't protect against integrity violations. Examples: using untrusted CDNs for scripts, insecure deserialization.
Fix: Verify integrity of dependencies (Subresource Integrity for CDN scripts), sign artifacts, and avoid deserializing untrusted data.
<script src="https://cdn.example.com/lib.js"
integrity="sha384-..."
crossorigin="anonymous"></script>
A09: Security Logging and Monitoring Failures
Without logging and monitoring, breaches go undetected. Insufficient logging means you can't investigate incidents.
Fix: Log authentication events, access control failures, and input validation failures. Ensure logs are tamper-evident and monitored. Set up alerts for suspicious activity.
A10: Server-Side Request Forgery (SSRF)
SSRF occurs when an application fetches a remote resource without validating the user-supplied URL. An attacker can make the server connect to internal services.
// Vulnerable: fetches any URL
app.get('/fetch', async (req, res) => {
const response = await fetch(req.query.url);
res.send(await response.text());
});
Fix: Validate and sanitize URLs. Use an allowlist of allowed domains and protocols. Block private IP ranges.
const allowedHosts = ['api.example.com', 'cdn.example.com'];
const url = new URL(req.query.url);
if (!allowedHosts.includes(url.hostname)) {
return res.status(400).send('Invalid host');
}
Quick Reference Table
| Risk | Example | Primary Fix |
|---|---|---|
| A01 Broken Access Control | Access other users' data via ID | Enforce authorization checks |
| A02 Cryptographic Failures | Plaintext passwords | Use bcrypt/Argon2, HTTPS |
| A03 Injection | SQL injection via concatenation | Parameterized queries |
| A04 Insecure Design | Guessable security questions | Threat modeling |
| A05 Security Misconfiguration | Default credentials | Harden config, security headers |
| A06 Vulnerable Components | Outdated library with CVE | Regular updates, audit |
| A07 Auth Failures | No rate limiting on login | MFA, strong policies |
| A08 Integrity Failures | Unverified CDN script | Subresource Integrity |
| A09 Logging Failures | No logs of failed logins | Centralized logging, alerts |
| A10 SSRF | Fetch internal metadata URL | Allowlist, block private IPs |
How to Apply the OWASP Top 10 in Your Workflow
- During design: Use threat modeling to identify risks early.
- During coding: Follow secure coding guidelines and use linters with security rules.
- During code review: Check for common pitfalls like missing authorization or input validation.
- In CI/CD: Integrate dependency scanning and static analysis.
- In production: Monitor logs, set up alerts, and conduct regular penetration tests.
FAQ
What is the OWASP Top 10?
The OWASP Top 10 is a regularly updated list of the most critical security risks for web applications, published by the Open Worldwide Application Security Project. It serves as a baseline for developers to prioritize security efforts.
How often is the OWASP Top 10 updated?
The list is updated every few years based on data from security experts and real-world vulnerabilities. The most recent version is from 2021, but it remains a relevant guide until the next update.
Can I rely solely on the OWASP Top 10 for security?
No. The OWASP Top 10 covers the most common risks but is not exhaustive. You should also follow secure coding practices, conduct regular security testing, and stay informed about emerging threats.
For a quick security check, you can use the JSON Formatter to inspect API responses for sensitive data leakage—a simple step that helps prevent cryptographic failures and information exposure.