Web Security Fundamentals: OWASP Top 10 and Beyond
A comprehensive guide to web application security covering the OWASP Top 10 vulnerabilities, defense in depth strategies, and secure development lifecycle practices.
Why Web Security Matters
Web applications are the primary interface between organizations and their users. They handle sensitive data — personal information, payment details, medical records — and they run on complex technology stacks that span client browsers, application servers, databases, APIs, third-party services, and cloud infrastructure. Each component introduces potential vulnerabilities.
In 2026, web applications remain the most targeted attack vector. Understanding the OWASP Top 10 and implementing defense in depth is essential for anyone building or securing modern web applications.
How the Web Works
Before you can secure a web application, you need to understand how the web works at a fundamental level.
The HTTP Request Lifecycle
Every time you visit a web page, your browser goes through this sequence:
This entire process typically completes in under one second for a well-optimized site.
{@visual http-request-flow}
Client-Side vs Server-Side
Understanding where code executes is critical for security:
Client-Side (browser):
Server-Side (web server, application server):
{@visual web-app-stack}
HTTP Protocol Deep Dive
HTTP Methods
| Method | Purpose | Safe | Idempotent | Body |
|--------|---------|------|------------|------|
| GET | Retrieve a resource | Yes | Yes | No |
| POST | Create a resource | No | No | Yes |
| PUT | Update/replace a resource | No | Yes | Yes |
| PATCH | Partial update | No | No | Yes |
| DELETE | Remove a resource | No | Yes | No |
| HEAD | Get headers only | Yes | Yes | No |
| OPTIONS | Discover allowed methods | Yes | Yes | No |
Safe means the request does not modify server state. Idempotent means multiple identical requests produce the same result.
HTTP Request Structure
GET /api/users HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64)
Authorization: Bearer eyJhbGciOiJI...
Accept: application/json
Content-Type: application/json
HTTP Response Structure
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 342
X-Content-Type-Options: nosniff
Strict-Transport-Security: max-age=31536000
{"users":[{"id":1,"name":"Alice"}]}
HTTP Status Code Classes
| Code Range | Class | Meaning |
|-----------|-------|---------|
| 1xx | Informational | Request received, continuing |
| 2xx | Success | Request received, understood, accepted |
| 3xx | Redirection | Further action needed |
| 4xx | Client Error | Request has bad syntax or cannot be fulfilled |
| 5xx | Server Error | Server failed to fulfill a valid request |
Key Status Codes
| Code | Meaning | Typical Cause |
|------|---------|---------------|
| 200 | OK | Request succeeded |
| 201 | Created | Resource created via POST |
| 301 | Moved Permanently | URL changed permanently |
| 302 | Found (Temporary Redirect) | URL changed temporarily |
| 304 | Not Modified | Cache is valid |
| 400 | Bad Request | Malformed request syntax |
| 401 | Unauthorized | Missing or invalid authentication |
| 403 | Forbidden | Authenticated but not authorized |
| 404 | Not Found | Resource does not exist |
| 405 | Method Not Allowed | Wrong HTTP method |
| 429 | Too Many Requests | Rate limit exceeded |
| 500 | Internal Server Error | Server-side error |
| 502 | Bad Gateway | Upstream server error |
| 503 | Service Unavailable | Server overloaded or down |
HTTPS and TLS
Why HTTPS Matters
HTTP sends all data in plaintext. Anyone on the network path — Wi-Fi hotspot, ISP, corporate proxy, attacker on the same network — can read every request and response. HTTPS encrypts the entire communication using TLS (Transport Layer Security).
The TLS Handshake
The TLS handshake establishes an encrypted connection between client and server:
In TLS 1.3, this completes in a single round trip (1-RTT), making it faster than previous versions.
{@visual https-tls-handshake}
Comparison: HTTP vs HTTPS
| Feature | HTTP | HTTPS |
|---------|------|-------|
| Encryption | None (plaintext) | TLS encryption |
| Default Port | 80 | 443 |
| Authentication | None | Server certificate verified by CA |
| Data Integrity | None (can be modified in transit) | Cryptographic integrity verification |
| SEO Impact | Negative (Chrome marks as "Not Secure") | Positive (Google ranking signal) |
| Performance | Slightly faster (no TLS overhead) | Minimal overhead with modern hardware |
| Required For | Nothing modern | HTTP/2, HTTP/3, Service Workers, Geolocation API |
| Certificate | Not needed | Required from a trusted CA |
How Browsers Use the Network Tab
Browser Developer Tools are essential for understanding web security. Open them with F12 or Ctrl+Shift+I.
Network Tab Walkthrough
Open the Network tab, visit any website, and observe:
Practical Example
# Using curl to inspect headers (same as browser Network tab)
curl -I https://example.com
HTTP/2 200
content-encoding: br
content-type: text/html; charset=UTF-8
server: Apache
strict-transport-security: max-age=63072000
x-content-type-options: nosniff
x-frame-options: DENY
{@visual devtools-network-tab}
Cookies, Sessions, and Authentication
How Cookies Work
Cookies are small pieces of data that the server sends to the browser, which the browser stores and sends back with every subsequent request to the same domain.
Cookie Attributes:
| Attribute | Purpose | Security Implication |
|-----------|---------|---------------------|
| HttpOnly | Prevents JavaScript access to the cookie | Prevents XSS from stealing cookies |
| Secure | Cookie only sent over HTTPS | Prevents exposure on HTTP connections |
| SameSite | Controls when cookies are sent cross-site | Prevents CSRF attacks |
| Domain | Which domain receives the cookie | Overly broad domains leak cookies |
| Path | Which URL path receives the cookie | Narrow paths reduce exposure |
| Expires/Max-Age | Cookie lifetime | Shorter lifetimes reduce window of attack |
Sessions vs Cookies
| Feature | Cookies | Sessions |
|---------|---------|----------|
| Storage Location | Browser (client-side) | Server (in memory, database, or Redis) |
| Data Exposure | Visible to user, can be modified | Hidden on server, user cannot modify |
| Size Limit | 4KB per cookie | Limited by server memory/storage |
| Expiration | Set by Expires/Max-Age | Server-controlled, can be invalidated immediately |
| Security | Must use HttpOnly + Secure + SameSite | Server controls the data, only session ID in cookie |
Best Practice: Store only a session identifier in the cookie. Store all sensitive data on the server side, keyed by that session ID.
{@visual cookie-session-lifecycle}
Authentication vs Authorization
| Concept | Authentication (AuthN) | Authorization (AuthZ) |
|---------|----------------------|----------------------|
| Question | "Who are you?" | "What can you do?" |
| Mechanism | Username/password, MFA, OAuth | Roles, permissions, policies |
| Failure | Login denied | 403 Forbidden |
| Token | ID Token (JWT) | Access Token (JWT) with claims |
| OWASP Category | A07: Identification and Authentication Failures | A01: Broken Access Control |
{@visual auth-flow}
JWT (JSON Web Tokens)
JWTs are self-contained tokens that encode claims in a base64-encoded JSON payload, signed with a secret or public/private key pair.
# A JWT consists of three parts separated by dots:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInJvbGUiOiJhZG1pbiJ9.dQw4w9WgXcQ
# Header: {"alg":"HS256","typ":"JWT"}
# Payload: {"userId":1,"role":"admin"}
# Signature: HMACSHA256(base64UrlEncode(header)+"."+base64UrlEncode(payload), secret)
JWT Security Checklist:
Same-Origin Policy and CORS
Same-Origin Policy (SOP)
SOP is a fundamental browser security mechanism that restricts how a document or script loaded from one origin can interact with resources from another origin. Two URLs have the same origin if they share the same protocol, host, and port.
https://example.com/page1
https://example.com/page2 # Same origin
https://api.example.com # Different origin (subdomain)
http://example.com # Different origin (protocol)
https://example.com:8080 # Different origin (port)
Cross-Origin Resource Sharing (CORS)
CORS is a mechanism that allows servers to relax SOP restrictions for specific cross-origin requests. The server includes HTTP headers that tell the browser which origins are permitted.
# Server response allowing cross-origin requests
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 3600
Common CORS Mistakes:
Terminal Sessions for Web Security
curl Examples
# Basic GET request
curl https://example.com
# View response headers only
curl -I https://example.com
# POST request with JSON data
curl -X POST https://api.example.com/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"secret"}'
# Include cookies
curl -b "sessionid=abc123" https://example.com/dashboard
# Follow redirects
curl -L http://example.com
# Show full request and response details
curl -v https://example.com
# Use a specific HTTP method
curl -X PUT -d '{"name":"updated"}' https://api.example.com/resource/1
openssl s_client (Inspect TLS)
# Connect to a server and show the TLS handshake details
openssl s_client -connect example.com:443 -servername example.com
# Show certificate chain
openssl s_client -connect example.com:443 -showcerts
# Check if a server supports TLS 1.3
openssl s_client -connect example.com:443 -tls1_3
DNS Tools
# dig — Detailed DNS lookup
dig example.com
dig example.com MX
dig +trace example.com
# host — Simple DNS lookup
host example.com
host -t MX example.com
# nslookup — Interactive DNS tool
nslookup example.com
nslookup -type=any example.com
Network Diagnostics
# ping — Test basic connectivity
ping -c 4 example.com
# traceroute — Map network path
traceroute example.com
# Test specific port connectivity
nc -zv example.com 443
timeout 2 bash -c "echo >/dev/tcp/example.com/80" && echo "Port 80 open"
Python HTTP Server
# Serve the current directory on port 8000
python3 -m http.server 8000
# This is useful for:
# - Testing local files in a browser-like environment
# - Creating a quick file sharing endpoint
# - Testing webhooks locally with ngrok
# WARNING: Do not use this in production — no security features
Burp Suite Walkthrough
Burp Suite is the industry-standard tool for web application security testing. The Community Edition is free and sufficient for learning.
Setting Up Burp Suite
Configuring Your Browser
To route browser traffic through Burp's proxy:
Proxy Tab
The Proxy tab shows all requests passing through Burp:
Intercepting and Modifying Requests
When Intercept is on, every request pauses in Burp:
# Example intercepted request
GET /login HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Cookie: sessionid=abc123
username=admin&password=secret
You can modify any part — URL, headers, body — before clicking "Forward" to send it to the server. This is how you test for vulnerabilities like parameter tampering, SQL injection, and access control bypasses.
Repeater
The Repeater tab lets you resend individual requests and observe responses. Use it to:
{@visual burp-proxy-intercept}
Decoder
The Decoder tab converts between encodings:
Comparer
The Comparer tab highlights differences between two requests or responses. Use it to:
Target
The Target tab shows a site map of discovered endpoints, parameters, and content. It automatically builds this from proxied traffic and is useful for understanding the application's attack surface.
{@visual burp-proxy-intercept}
OWASP Top 10 2021
The Open Web Application Security Project (OWASP) Top 10 is the definitive guide to the most critical web application security risks. Updated periodically, it represents a broad consensus among security experts about the most important vulnerabilities.
A01: Broken Access Control
Access control enforces what users can do within an application. Broken access control occurs when these restrictions are not properly implemented.
Common examples include privilege escalation (a regular user accessing admin functions), insecure direct object references (IDOR — changing a URL parameter like /user/123 to /user/456 to access another user's data), and missing restrictions on API endpoints.
Prevention: Implement role-based access control (RBAC) with server-side enforcement, deny access by default, validate permissions on every request, and use random or hashed identifiers instead of sequential IDs.
Real-World Impact: The 2021 T-Mobile breach exposed data of 40 million people through an insecure API endpoint with broken access control.
A02: Cryptographic Failures
Previously titled "Sensitive Data Exposure," this category focuses on failures related to cryptography. Examples include transmitting data without TLS, storing passwords with weak hashing algorithms (MD5, SHA1), using outdated ciphers, and hardcoding cryptographic keys.
Prevention: Use TLS 1.3 everywhere, hash passwords with bcrypt/argon2, encrypt sensitive data at rest, never hardcode secrets, and use established cryptographic libraries rather than implementing your own.
A03: Injection
Injection attacks occur when untrusted data is sent to an interpreter as part of a command or query. SQL injection is the most well-known, but command injection, LDAP injection, and NoSQL injection are also common.
-- Vulnerable SQL query (concatenation)
SELECT * FROM users WHERE username = '" + userInput + "' AND password = '" + passInput + "'
-- If userInput = admin' --, the query becomes:
SELECT * FROM users WHERE username = 'admin' --' AND password = ''
-- This bypasses authentication entirely!
Prevention: Use parameterized queries (prepared statements) for database access, employ input validation and parameterization for all interpreters, escape special characters, and use ORM frameworks that handle query construction safely.
A04: Insecure Design
This newer category highlights the importance of security-by-design — building security into the application architecture from the start rather than bolting it on later. Issues include missing threat modeling, inadequate rate limiting, and lack of secure defaults.
Prevention: Integrate security into the design phase using threat modeling (STRIDE, PASTA), establish secure design patterns, and require security reviews for architectural changes.
A05: Security Misconfiguration
Applications often ship with insecure default configurations. Common problems include enabling unnecessary services, using default credentials, exposing directory listings, verbose error messages revealing stack traces, and failing to patch or update components.
Prevention: Automate configuration management with infrastructure-as-code, disable unnecessary features, enforce secure defaults, and regularly scan for misconfigurations.
A06: Vulnerable and Outdated Components
Modern applications depend heavily on third-party libraries and frameworks. These dependencies can introduce known vulnerabilities that attackers can exploit.
Prevention: Maintain an inventory of all components and their versions (software bill of materials — SBOM), regularly scan for known vulnerabilities (CVE databases, Snyk, OWASP Dependency-Check), update dependencies promptly, and remove unused dependencies.
A07: Identification and Authentication Failures
Weak authentication mechanisms include allowing weak passwords, not implementing MFA, exposing session identifiers in URLs, and failing to invalidate sessions on logout.
Prevention: Enforce strong password policies, implement MFA, use secure session management (HttpOnly, Secure, SameSite cookies), limit login attempts, and implement proper session expiration.
A08: Software and Data Integrity Failures
This category covers failures related to integrity verification. Examples include using untrusted third-party CDNs, accepting deserialized data without validation, and failing to verify software update signatures.
Prevention: Use subresource integrity (SRI) for CDN resources, sign and verify software updates, validate serialized data, and verify the integrity of CI/CD pipeline artifacts.
A09: Security Logging and Monitoring Failures
Without adequate logging and monitoring, breaches go undetected for months. The average dwell time (time between intrusion and detection) is over 200 days.
Prevention: Log all authentication attempts (successful and failed), access control failures, input validation errors, and administrative actions. Use centralized logging with SIEM integration, protect logs from tampering, and establish alerting thresholds.
A10: Server-Side Request Forgery (SSRF)
SSRF occurs when an attacker can trick the server into making requests to internal resources. This can expose internal services, cloud metadata endpoints, and other sensitive infrastructure.
Prevention: Validate and sanitize all URLs provided by users, restrict outbound traffic from application servers, block access to private IP ranges, and avoid passing raw URLs to network functions.
Defense in Depth
No single security control is sufficient. Defense in depth layers multiple controls so that if one fails, others still provide protection.
Web Application Firewall (WAF)
A WAF filters HTTP traffic between the client and the application, blocking common attack patterns like SQL injection and XSS. Cloud WAF services (Cloudflare, AWS WAF, ModSecurity) offer managed rule sets and are easy to deploy.
Content Security Policy (CSP)
CSP is an HTTP header that tells the browser which sources of content are allowed to load:
# Restrictive CSP
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; frame-ancestors 'none'
A well-crafted CSP prevents XSS by blocking inline scripts and restricting script sources, and can eliminate data exfiltration by restricting connection destinations.
Input Validation
Validate all input on the server side (client-side validation is for user experience, not security). Use allow lists of acceptable values rather than deny lists of dangerous patterns. Validate type, length, format, and range.
Output Encoding
Encode dynamic content before rendering it in the browser to prevent XSS attacks. Use contextual encoding — HTML encoding for HTML contexts (<), URL encoding for URLs (%3C), JavaScript encoding for script contexts.
Security Headers
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
Content-Security-Policy: default-src 'self'
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: camera=(), microphone=(), geolocation=()
These headers add additional protection layers with minimal performance cost.
Practical Labs
Lab 1: Inspecting a Real Website
Objective: Use browser Developer Tools to inspect HTTP traffic.
Setup: Open Chrome/Firefox Developer Tools (F12), click the Network tab, visit any website.
Commands: Filter by "XHR" to see API calls, click any request to view headers and response.
Expected Observations: See DNS timings, TLS handshake duration, request and response headers, cookie exchange, and status codes.
Safety Notes: You are only observing traffic to a public website you have deliberately visited. This is safe and legal.
Lab 2: Testing with Burp Suite
Objective: Intercept and modify HTTP requests using Burp Suite.
Setup: Install Burp Suite (comes pre-installed on Kali), configure Firefox proxy to 127.0.0.1:8080, install Burp CA certificate.
Steps:
Safety Notes: Only practice on sites you own or have explicit permission to test.
Lab 3: SQL Injection on DVWA
Objective: Perform a basic SQL injection attack on DVWA in a safe local environment.
Setup: Install and run DVWA locally using Docker or XAMPP. Set security level to Low.
Steps:
Cleanup: Reset DVWA to high security level.
Safety Notes: Only run DVWA on a local, isolated environment. Never test against external systems.
Common Beginner Mistakes
1. Ignoring HTTPS
2. Trusting Client-Side Validation
3. Using GET Requests for Sensitive Data
4. Weak Session Management
5. Insecure Cookie Configuration
6. Poor CORS Configuration
7. Storing Secrets in Code
8. Not Validating Content Types
9. Exposing Stack Traces
10. Ignoring Subresource Integrity (SRI)
11. Missing Rate Limiting
12. Weak Password Policies
13. Not Implementing Account Lockout
14. Using Unvalidated Redirects
15. Forgetting to Invalidate Sessions on Logout
Troubleshooting
Mixed Content
Certificate Errors
CORS Failures
403 Forbidden
404 Not Found
500 Internal Server Error
CSRF Token Mismatch
Cookie Not Set
DNS Resolution Failure
Connection Refused
Detection & Defense
Web Application Firewall (WAF)
WAFs examine HTTP traffic at the application layer and block malicious requests before they reach the application.
Content Security Policy (CSP)
CSP is your strongest defense against XSS. A strict CSP:
# Strict CSP that allows only same-origin resources and blocks inline scripts
Content-Security-Policy: default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'
Secure Headers Checklist
Input Validation Rules
Output Encoding by Context
| Context | Encoding | Example |
|---------|----------|---------|
| HTML body | HTML entity encode | <script> |
| HTML attribute | HTML attribute encode | " |
| JavaScript string | JavaScript string encode | \x3Cscript\x3E |
| URL parameter | URL encode | %3Cscript%3E |
| CSS string | CSS escape | \3C script\3E |
Rate Limiting
Logging Requirements
Monitoring
Secure Development Lifecycle (SDL)
Integrate security into every phase of development:
Web security is not a one-time checklist — it is an ongoing practice. The OWASP Top 10 provides the starting point, but defense in depth and a secure development lifecycle are what truly protect applications in production.
{@visual attack-chain-web}
Glossary
| Term | Definition |
|------|-----------|
| Authentication (AuthN) | The process of verifying who a user is (e.g., username/password, MFA) |
| Authorization (AuthZ) | The process of determining what a user can do after authentication |
| CORS | Cross-Origin Resource Sharing — a mechanism that allows controlled cross-origin requests |
| CSP | Content Security Policy — an HTTP header that restricts which resources a browser can load |
| CSRF | Cross-Site Request Forgery — an attack that tricks a user into performing unwanted actions |
| Cookie | A small piece of data stored by the browser and sent with each request to the originating domain |
| DNS | Domain Name System — translates domain names to IP addresses |
| HSTS | HTTP Strict Transport Security — instructs browsers to always use HTTPS |
| HTTP | Hypertext Transfer Protocol — the foundation protocol for web communication |
| HTTPS | HTTP over TLS — encrypted HTTP communication |
| Injection | An attack where untrusted data is sent to an interpreter as part of a command or query |
| JWT | JSON Web Token — a self-contained token format for transmitting claims securely |
| MFA | Multi-Factor Authentication — requiring two or more verification factors |
| MITM | Man-in-the-Middle — an attack where the attacker intercepts communication between two parties |
| ORM | Object-Relational Mapping — a technique for converting data between incompatible type systems |
| OWASP | Open Web Application Security Project — a nonprofit focused on improving software security |
| RBAC | Role-Based Access Control — restricting access based on user roles |
| SIEM | Security Information and Event Management — centralized logging and analysis system |
| SOP | Same-Origin Policy — a browser security mechanism restricting cross-origin interactions |
| SSRF | Server-Side Request Forgery — an attack that tricks the server into making internal requests |
| TLS | Transport Layer Security — cryptographic protocol for secure communication |
| WAF | Web Application Firewall — filters HTTP traffic to block common attack patterns |
| XSS | Cross-Site Scripting — injection of malicious scripts into web pages viewed by others |
| SQLi | SQL Injection — injection attack targeting database queries |
References
{@ref owasp-top10}
{@ref owasp-testing-guide}
{@ref owasp-cheatsheet}
{@ref owasp-asvs}
{@ref mdn-http}
{@ref mdn-cors}
{@ref burpsuite-docs}
{@ref rfc2616}
{@ref rfc7230}
{@ref rfc8446}
{@ref rfc6265}
{@ref rfc7519}
{@ref nist-sp800-115}
{@ref nist-csf}