Skip to content

Web Security

162 companion flashcards · AI-assisted study content · Open the deck →

deck offers a friendly introduction to web security, covering the core concepts every developer or curious learner should know. You'll work through foundational questions about what web security is and why it matters, then move into key topics like authentication, authorization, and the principle of least privilege. The cards also tackle common attack types such as SQL injection, cross-site scripting, and cross-site request forgery, along with the practical defenses used to counter each one.

It's well suited for beginners who are just starting to explore application security, as well as developers who want a quick refresher on terminology and best practices. If you're studying for an interview, building a web app, or simply want to understand how to keep a site safer, these flashcards will help you build a solid mental framework for thinking about threats and protections.

Because many of these concepts build on one another, try reviewing the cards in small sets over several days rather than cramming them all at once. When you come across a term like XSS or CSRF, take a moment to think of a concrete example, since linking the idea to a real scenario will make it stick much better during future reviews.

Foundations of Web Security

Web security is the practice of protecting web applications, the users who interact with them, and the data they handle from malicious access, misuse, and disruption. Security failures do more than cause outages — they erode user trust, expose sensitive data, and can create legal liability, financial loss, and long-term operational harm. Treating security as a core feature, not an afterthought, is what separates resilient systems from fragile ones.

Two concepts sit at the center of most access decisions. Authentication answers the question "who is making this request?" by verifying identity, usually at login. Authorization comes after, deciding what an already-authenticated user is allowed to see or do. Conflating these is a common source of bugs. Closely related is the principle of least privilege: every user, service, and process should receive only the minimum access needed for its task. Combined with a secure-by-default and deny-by-default stance, this keeps blast radius small when something does go wrong.

Good web security is also proactive. Threat modeling identifies likely attackers, valuable assets, and entry points before code is written, while security reviews done early in design are far cheaper than retrofitting fixes after assumptions have shipped. A related idea is defense in depth: layering independent controls so that a single failure — a missed input check, a leaked token, a misconfigured header — does not fully compromise the system. Fail-closed behavior, where a security control denies access when it cannot decide, is generally safer than failing open. Practically, this means treating all untrusted input as hostile, keeping dependencies current, designing for least privilege by default, and assuming attackers will probe every exposed boundary.

Common Web Vulnerabilities

Despite decades of awareness, the same families of flaws keep appearing in web applications. Injection attacks lead the list. SQL injection happens when untrusted input is concatenated into a query, allowing attackers to alter its structure. Variants include UNION-based attacks that append rows from arbitrary tables, blind SQLi where results are not directly returned and data must be inferred from boolean or timing side channels, and second-order SQLi where input is stored safely but later concatenated in a different context. Path traversal uses sequences like "../../" in file-related input to escape intended directories. CRLF injection smuggles carriage return or line feed characters into headers or logs, enabling response splitting, while HTTP request smuggling exploits disagreements between front-end and back-end parsers about Content-Length versus Transfer-Encoding: chunked.

Cross-site issues affect users through their browsers. Reflected XSS echoes attacker-supplied script from a request (often in a URL) directly back to the victim. Stored XSS persists a payload on the server — in a comment, profile field, or similar — so it runs for every viewer of the affected page. DOM-based XSS exists entirely in client-side JavaScript that reads an attacker-controllable source (such as location.hash) and writes it to a dangerous sink. Cross-Site Request Forgery (CSRF) tricks an already-authenticated browser into submitting a state-changing request the user never intended. Clickjacking is related but distinct: it overlays disguised UI so the user clicks something other than what they see.

Authorization flaws form a third major category. Insecure Direct Object References (IDOR) occur when an app uses a user-supplied identifier to fetch an object without verifying the requester is allowed to see it; horizontal privilege escalation is accessing another user's data at the same level, while vertical escalation is gaining higher privilege (for example, becoming an admin). Server-Side Request Forgery (SSRF) tricks the server into issuing requests to unintended targets, often internal services or cloud metadata endpoints like IMDS, and URL parser confusion can make "validated" URLs resolve to hidden hosts. XML External Entity (XXE) attacks abuse DTD processing to read files or pivot SSRF. Finally, mass assignment binds every incoming request field to a model (letting an attacker set fields like is_admin), prototype pollution mutates Object.prototype through unsafe deep-merges in JavaScript, and insecure deserialization turns untrusted serialized data into live objects capable of remote code execution, replay, or privilege escalation.

Defensive Coding Practices

Most web vulnerabilities can be prevented at the point where untrusted data meets code. Input validation is the first line: incoming data should be checked for expected type, format, length, and constraints before it is processed further. Client-side validation still has a place because it improves user experience, but it must never be relied on for security — attackers bypass it trivially. Where possible, allowlists (permitting only known-good values) are far safer than blocklists (rejecting known-bad patterns), because allowlists fail closed against novel attacks.

For SQL and similar databases, parameterized queries (also called prepared statements) separate the query structure from the data: the database compiles the SQL once, and user input is bound as values rather than spliced in as code. This single discipline reliably prevents SQL injection. For output, escaping ensures untrusted content is treated as data, not executable code. HTML escaping neutralizes characters for safe insertion into HTML text or attributes, while JavaScript escaping does the same inside JS string literals or blocks — confusing the two is a common XSS vector. Correct Content-Type headers also matter: without X-Content-Type-Options: nosniff, browsers may MIME-sniff a response and interpret a text/plain upload as HTML or script.

Beyond code-level controls, Content Security Policy (CSP) lets a server instruct the browser to restrict what scripts, styles, and resources can load. A strict policy avoids 'unsafe-inline' (which neuters most XSS protection) and 'unsafe-eval' (which permits eval and string-based code construction); nonce-based scripts and 'strict-dynamic' trust scripts loaded by a nonce-bearing script, avoiding brittle CDN allowlists. Subresource Integrity (SRI) hashes verify that a fetched script or stylesheet matches a known digest, so a compromised CDN cannot serve altered code. For third-party scripts specifically, the safest pattern is to pin exact versions, serve them yourself when possible, isolate them in sandboxed iframes with a strict CSP, and review what data they collect. None of these replaces secure code — a Web Application Firewall (WAF) inspects HTTP traffic for known-bad patterns but can be bypassed with encoding, parameter pollution, or novel payloads and adds latency and false positives — but together they form effective defense in depth.

Authentication, Sessions, and Password Security

Authentication verifies identity, and session management maintains that authenticated state across subsequent requests, usually by issuing a session ID cookie. The two must not be confused: a strong login cannot save an application whose session IDs are guessable, reused, or never rotated. Session token entropy should be at least 128 bits drawn from a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG) like /dev/urandom or crypto.randomBytes, not from generic RNGs such as rand() or Math.random(). After login, the session ID should be rotated to defeat session fixation, where an attacker plants a known identifier on the victim beforehand. Storing privileged state in the session (and never in client-side tokens that the server does not re-check) helps prevent privilege escalation, and sending a clear audit trail of important actions supports investigation and accountability.

Password storage is its own discipline because hashes leak. Secure storage uses strong one-way hashing with a unique salt per password so precomputed rainbow tables are useless. Password stretching (bcrypt cost, PBKDF2 iteration count, or Argon2) makes each guess expensive, and modern APIs like PHP's password_hash with PASSWORD_BCRYPT or PASSWORD_ARGON2ID handle salts and algorithm choice correctly. Plain SHA-256 is far too fast for password hashing — GPUs can test billions per second. A pepper is a server-side secret added on top of the salt: even if the database is stolen, attackers without the pepper cannot crack hashes offline. Comparisons of hashes and HMACs must run in constant time to avoid timing oracles that leak information byte by byte, and authentication code paths should avoid revealing whether the username or the password was wrong in measurably different ways.

Cookies carry this session state and must be configured defensively. Secure means HTTPS-only, HttpOnly blocks JavaScript access (reducing the impact of XSS), and SameSite restricts cross-site sending. SameSite=Strict prevents the cookie from being sent on any cross-site request, including top-level navigations, breaking some login flows but maximizing CSRF protection; SameSite=Lax allows the cookie on top-level navigations but blocks most other cross-site requests, balancing usability and security. Cookie name prefixes add further guarantees: __Host- requires Secure, no Domain attribute, and Path=/ (binding the cookie to the exact host, preventing subdomain cookie tossing), while __Secure- requires Secure so the cookie cannot be silently downgraded to HTTP.

Beyond cookies, CSRF defenses often rely on tokens. The synchronizer token pattern binds a random CSRF token to the user's session and rejects state-changing requests without a valid match. The double-submit cookie pattern sets a CSRF cookie and expects the client to echo its value in a header; because attackers cannot read the cookie cross-site, the values will not match. SameSite=Lax already blocks many cross-site POSTs, but legacy apps and certain flows still need explicit tokens for defense in depth. Multi-factor authentication (MFA) strengthens login but is not a silver bullet: push-based MFA is vulnerable to MFA fatigue (spamming the user until they approve), browsers and password managers are vulnerable to session theft after MFA, and phishing sites can still capture one-time codes — phishing-resistant factors like FIDO2/WebAuthn security keys and device-bound passkeys bind the credential to the legitimate origin. Security questions are a weak factor because they rely on public or guessable facts. CAPTCHAs slow automated abuse like credential stuffing but are increasingly bypassable and should be one layer, not the only one.

HTTP Headers, CORS, and Transport Security

The browser is a willing ally when given the right instructions. Security headers are HTTP response headers that add browser-side protections with little implementation effort. Content-Security-Policy restricts which scripts, styles, and resources may load — and crucially which can be embedded as frames via frame-ancestors, which replaces the older X-Frame-Options. X-Frame-Options: DENY forbids framing entirely (maximum clickjacking protection), while SAMEORIGIN allows only same-origin framing. X-Content-Type-Options: nosniff tells browsers not to MIME-sniff away from the declared Content-Type, reducing content-type confusion attacks. Referrer-Policy controls how much of the URL is sent in the Referer header on outbound navigation, limiting leakage of sensitive paths or query parameters. The headers Sec-Fetch-Site, Sec-Fetch-Mode, and Sec-Fetch-Dest help servers understand a request's origin relationship, useful for origin validation.

Transport security deserves equal attention. HTTPS encrypts traffic in transit and prevents tampering between client and server; the HTTP Strict Transport Security (HSTS) header instructs browsers to only contact the site over HTTPS for a max-age period, defeating TLS downgrade attacks. POODLE (Padding Oracle On Downgraded Legacy Encryption) showed what happens when downgrade to SSL 3.0 is allowed, and Heartbleed (CVE-2014-0160) demonstrated that implementation bugs in TLS libraries can leak server memory, including private keys and session tokens. Mitigation strategies also include certificate pinning — restricting which certificates the client will trust for a host — and DNSSEC, which cryptographically signs DNS records so clients can verify answers were not tampered with in transit. Mixed content (an HTTPS page loading subresources over HTTP) breaks these guarantees and is blocked by modern browsers.

The Same-Origin Policy (SOP) is the browser rule that scripts from one origin can normally only read responses from the same origin (scheme + host + port). Same-site is looser, matching only the eTLD+1 (so a.example and b.example qualify), which is what SameSite cookies use. Cross-Origin Resource Sharing (CORS) is a controlled relaxation of SOP: a server opts in via headers such as Access-Control-Allow-Origin, and the browser sends a preflight OPTIONS request for non-simple requests to confirm allowed methods, headers, and origins. Two recurring mistakes break CORS: reflecting the Origin header into Access-Control-Allow-Origin (effectively disabling SOP for any attacker site) and combining Access-Control-Allow-Credentials: true with a wildcard or reflected origin, which lets third-party sites read authenticated responses. CORS is explicitly not an authentication or authorization mechanism — the server must still authorize every request.

Industry References and Token-Based API Security

Several community references anchor day-to-day security work. The OWASP Top 10 is a regularly updated list of the ten most critical web application security risks, published by the Open Worldwide Application Security Project. Common Weakness Enumeration (CWE) is a community-developed catalog of software and hardware weaknesses, each with a unique CWE-ID, while Common Vulnerabilities and Exposures (CVE) assigns unique IDs to publicly known vulnerabilities. The Common Vulnerability Scoring System (CVSS) scores each vulnerability on a 0.0–10.0 scale based on impact, exploitability, and scope. Together, these help prioritize patches, communicate risk, and standardize reporting across teams and vendors.

Threat modeling frameworks such as STRIDE categorize what can go wrong for each system element into Spoofing, Tampering, Repudiation, Information Disclosure, Denial of Service, and Elevation of Privilege, while DREAD scores each threat on Damage, Reproducibility, Exploitability, Affected users, and Discoverability. More broadly, modern systems embrace zero trust architecture — assuming no implicit trust based on network location and verifying identity, device, and context for every request — and tightly manage the attack surface, meaning every endpoint, parameter, and API that accepts user input.

Token-based APIs have their own pitfalls. API keys are opaque long-lived identifiers identifying the calling application, while OAuth tokens (often JWTs) are scoped, time-limited credentials representing delegated user access. Putting authorization-relevant claims like roles in a JWT is dangerous if the server does not re-check them server-side, because clients cannot be trusted. Classic JWT issues include alg=none acceptance (allowing unsigned tokens) and key confusion between HS and RS algorithms, where a public RSA key gets used as an HMAC secret. Defensive tokens carry explicit aud (audience) claims so a token issued for service A is rejected by service B, iss (issuer) claims so relying parties accept only trusted issuers, and nbf/exp time-window claims so a leaked token has a bounded lifetime. Refresh tokens extend sessions but must be stored and rotated securely. Outside JWTs, HMAC-signed webhooks let receivers verify both integrity and authenticity of callbacks, and signature comparisons must run in constant time to prevent timing oracles. Nonces are single-use, server-tracked values that prevent replay of captured requests, and signed requests should include a bounded timestamp window so a captured signature cannot be reused indefinitely. Finally, logs often outlive production data paths and are far more widely accessed: secrets, Authorization headers, and tokens should never be logged in the clear, and detailed internal error messages should be avoided in user-facing responses because they leak infrastructure, query, and validation details useful to attackers.

Frequently asked questions

What is web security?

Web security is the practice of protecting web applications, users, and data from malicious access, misuse, or disruption.

What is a secure cookie setting?

A secure cookie is configured with attributes like Secure, HttpOnly, and SameSite to reduce theft and abuse.

What is threat modeling?

Threat modeling is the practice of identifying likely attackers, assets, entry points, and abuse scenarios before building or changing systems.

What is DOM-based XSS?

It is XSS where the vulnerability is in client-side JavaScript that reads an attacker-controllable source (like location.hash) and writes it to a dangerous sink.

What is SQL injection UNION-based attack?

It appends a UNION SELECT to append rows from another query to the result, allowing the attacker to read arbitrary tables.

What is certificate pinning?

It is when a client restricts which TLS certificates it will accept for a given host, reducing risk of mis-issued or rogue CAs.

What are the secure cookie attributes?

Secure (HTTPS only), HttpOnly (no JS access), SameSite=Lax or Strict (limits cross-site sending), and a tight Path/Domain scope.

What is a CSP report-only mode?

It is a Content-Security-Policy-Report-Only header that reports violations to a URI without enforcing, used to safely tune a strict policy.

What is the difference between throttling and lockout?

Throttling adds progressive delay between attempts (still allows access); lockout blocks attempts entirely for a period after a threshold.

What is Heartbleed?

It is a 2014 vulnerability in OpenSSL's heartbeat extension (CVE-2014-0160) that allowed reading server memory, exposing private keys and session tokens.

Drill this topic

162 flashcards on Web Security — free, no signup needed to start.

Study Web Security flashcards

LearnWiki pages are generated with AI assistance from LearnCoachAssist's reviewed study catalog and may contain errors — verify anything critical against your course materials.