Cyber Security • Application and Web Security

Web App Auth Pitfalls — Explain authentication/authorization pitfalls in web apps (conceptual)

Understanding how flawed authentication and authorization mechanisms expose web applications to devastating security breaches.

A protected digital shield with binary code and a secure lock for cyber security
Inside this lesson 10 sections 5 questions 7 figures

SECTION 1

Historical Context & Motivation

The history of web application security is, in many respects, the history of authentication and authorization failures. In the earliest days of the World Wide Web, most sites served static content and required no user identity management whatsoever. As e-commerce, online banking, and social networking emerged in the late 1990s, developers were forced to build authentication systems (verifying who a user is) and authorization systems (determining what that user may do) largely from scratch, often without established security engineering practices. The consequences of these ad-hoc designs have been staggering: billions of leaked credentials, massive financial fraud, and erosion of public trust in digital services.

Understanding the evolution of these failures provides essential context for modern secure development. Each major breach taught the industry a painful lesson, yet many of the same conceptual pitfalls persist today in different guises.

2000 • OWASP Founded

The Open Web Application Security Project was established to systematically catalog and address recurring web security flaws, including broken authentication and session management.

2004 • Session Hijacking Goes Mainstream

Widespread adoption of session cookies without the Secure or HttpOnly flags made session hijacking trivially exploitable over unencrypted HTTP connections, affecting major web platforms.

2012 • LinkedIn Credential Breach

Over 6.5 million unsalted SHA-1 password hashes were leaked from LinkedIn, demonstrating the catastrophic consequences of weak credential storage practices at scale.

2017 • Equifax IDOR & Privilege Escalation

The Equifax breach exposed 147 million records, partly due to authorization failures that allowed attackers to access data far beyond any legitimate scope once initial access was obtained.

2021 • OWASP Top 10 Reorganization

The OWASP Top 10 elevated Broken Access Control to the #1 position, recognizing authorization flaws as the single most prevalent category of web application vulnerability.

The central question this lesson addresses is deceptively simple: why do authentication and authorization continue to be among the most exploited vulnerability classes in web applications, and what conceptual errors lead developers to create these flaws? By examining the underlying principles, attack patterns, and design mistakes, we can build intuition for writing secure code from the outset.

SECTION 2

Core Principles & Definitions

Before dissecting specific pitfalls, it is essential to establish precise definitions. In security engineering, authentication and authorization are complementary but distinct mechanisms, and conflating the two is itself a common source of vulnerabilities. These core principles form the conceptual foundation upon which all secure web application identity management is built.

1

Authentication (AuthN)

The process of verifying a claimed identity. This answers the question "Are you really who you say you are?" Mechanisms include passwords, biometrics, certificates, and multi-factor tokens.
2

Authorization (AuthZ)

The process of determining whether an authenticated entity has permission to perform a requested action or access a resource. This answers "Are you allowed to do this?"
3

Session Management

The mechanism that maintains authenticated state across multiple HTTP requests. Since HTTP is stateless, sessions bridge the gap using tokens, cookies, or JWTs, making them a critical attack surface.
4

Principle of Least Privilege

Every user, process, or system component should operate with the minimum set of permissions necessary to accomplish its task. Violations of this principle are the root cause of most authorization vulnerabilities.
5

Defense in Depth

Security should be implemented in multiple overlapping layers so that the failure of any single control does not compromise the entire system. Auth pitfalls often arise when a single check is the only barrier.
✦

KEY TAKEAWAY

Think of authentication like showing your government-issued ID at a building entrance — it proves you are who you claim to be. Authorization is the keycard system inside the building — just because you passed the front door does not mean you can open every room. A system that confuses these two concepts is like a building where anyone with a valid ID gets master-key access to every floor. Most auth pitfalls stem from either weak identity verification, poor session continuity, or missing or bypassable permission checks.

SECTION 3

Visual Explanation — The Auth Flow Attack Surface

A typical web application authentication and authorization flow involves several stages, each of which presents a distinct attack surface. The diagram below traces a user request from initial login through session establishment and finally to a resource access decision, annotating the common pitfall categories at each stage.

Web App Authentication & Authorization Flow — Attack Surface MapUser / ClientBrowser / AppLogin EndpointCredential CheckSession ManagerToken / CookieAuthZ GatePermission Check⚠ PITFALL ZONE 1Credential StuffingBrute-Force AttacksWeak Password Policies⚠ PITFALL ZONE 2Plaintext StorageTiming Side-ChannelsMissing Rate Limiting⚠ PITFALL ZONE 3Session FixationToken PredictionMissing Expiration⚠ PITFALL ZONE 4IDOR VulnerabilitiesPrivilege EscalationMissing Server-Side ChecksCross-Cutting PitfallsInsecure Transport (HTTP)CSRF / XSS Token TheftInadequate LoggingApplies to all stagesApplies to all stagesApplies to all stagesLegendAuthN StageSession MgmtAuthZ GatePitfall ZoneCross-Cutting
The diagram traces a typical request from the User/Client through the Login Endpoint, Session Manager, and Authorization Gate. Each dashed red box identifies a pitfall zone with its associated vulnerability classes. The green cross-cutting bar at the bottom shows threats that span the entire pipeline.

Observe that the attack surface is not confined to a single stage. Pitfall Zone 1 targets the credential submission phase, where attackers exploit weak password policies or reuse credentials from other breaches. Pitfall Zone 2 targets the server-side credential validation logic, where insecure storage or timing leaks can undermine even strong passwords. Pitfall Zone 3 encompasses session management weaknesses such as predictable tokens or absent expiration policies. Finally, Pitfall Zone 4 — the authorization gate — is where Insecure Direct Object References (IDOR) and privilege escalation attacks occur. A secure application must defend every stage, because a failure at any single point can cascade into a full compromise.

SECTION 4

How Auth Pitfalls Work — Mechanisms in Depth

Authentication Pitfalls

Authentication vulnerabilities arise when the system fails to reliably verify a user's identity. The most common categories include credential stuffing, where attackers automate login attempts using username-password pairs leaked from other services; brute-force attacks, where systematically guessing credentials succeeds when rate limiting is absent; and insecure credential storage, where passwords are stored in plaintext, with weak hashing algorithms (e.g., unsalted MD5 or SHA-1), or without adaptive cost factors.

BRUTE-FORCE SEARCH SPACE

S=ClS = Cˡ

Where S is the total search space size, C is the character set cardinality (e.g., 95 for printable ASCII), and l is the password length. A policy requiring only 6-character lowercase passwords yields 26⁶ ≈ 3.09 × 10⁸ combinations — trivially brute-forcible on modern hardware. Increasing length to 12 with mixed case yields 52¹² ≈ 3.91 × 10²⁰, demonstrating the exponential benefit of length and character diversity.

Session Management Pitfalls

Once a user authenticates, the application must maintain that state across requests. Session fixation occurs when an application accepts an externally supplied session ID and does not regenerate it after successful login, allowing an attacker who set the initial ID to hijack the session. Session prediction exploits insufficient randomness in token generation — if tokens are derived from sequential counters or timestamps, an attacker can compute valid session IDs. The entropy of a session token quantifies its resistance to guessing.

SESSION TOKEN ENTROPY

H=log2(N)H = log₂(N)

Where H is the entropy in bits and N is the number of possible token values. OWASP recommends a minimum of 128 bits of entropy for session identifiers. A 32-character hexadecimal token provides 16³² = 2¹²⁸ possible values, yielding exactly 128 bits of entropy.

Authorization Pitfalls

Authorization failures are arguably the most dangerous class of auth pitfalls because they often grant attackers access to data or functionality belonging to other users. An Insecure Direct Object Reference (IDOR) occurs when the application uses a user-controllable parameter (e.g., /api/invoices/1042) to locate a resource without verifying that the authenticated user is authorized to access that specific object. Vertical privilege escalation occurs when a standard user accesses admin-only functionality, while horizontal privilege escalation occurs when a user accesses another same-role user's resources. Both result from missing or inadequate server-side permission checks, often because developers mistakenly rely on client-side UI restrictions (hiding buttons) as a security control.

⚠

Critical Misconception

Hiding a UI element (such as an admin panel link) is not authorization. If the server endpoint /admin/deleteUser?id=5 does not verify the caller's role, any authenticated user who discovers or guesses the URL can invoke it. All authorization must be enforced server-side.

SECTION 5

Taxonomy of Auth Pitfalls

Organizing authentication and authorization pitfalls into a structured taxonomy helps security engineers reason about coverage when performing threat modeling or code review. The following classification aligns with the OWASP Top 10 (2021) categories A01 (Broken Access Control) and A07 (Identification and Authentication Failures), while also mapping common weakness enumerations (CWEs) for reference.

Taxonomy of Web App Auth PitfallsAuth PitfallsAuthentication (AuthN)Session ManagementAuthorization (AuthZ)Credential Weaknesses• Weak password policy• Plaintext / weak hash• No saltingCWE-521, CWE-256CWE-916Auth Bypass• Credential stuffing• Brute-force (no lock)• Default credentialsCWE-307, CWE-798CWE-1391Token Weaknesses• Predictable IDs• Missing HttpOnly/Secure• No expiration/rotationCWE-330, CWE-614CWE-613Session Hijacking• Session fixation• XSS → cookie theft• Network sniffing (HTTP)CWE-384, CWE-79CWE-319Access Control• IDOR• Forced browsing• Path traversalCWE-639, CWE-425CWE-22Privilege Escalation• Vertical (user → admin)• Horizontal (user → user)• JWT claim tamperingCWE-269, CWE-862CWE-345
This taxonomy tree organizes auth pitfalls into three main branches: Authentication (credential weaknesses and auth bypass), Session Management (token weaknesses and session hijacking), and Authorization (access control failures and privilege escalation). CWE identifiers are provided for cross-referencing with vulnerability databases.
Pitfall CategoryOWASP Top 10 (2021)Impact LevelPrevalence
Broken Access Control (IDOR, Priv Esc)A01 — #1Critical94% of apps tested had some form
Identification & Auth FailuresA07 — #7HighCredential stuffing is automated at scale
Security Misconfiguration (Default Creds)A05 — #5High90% of apps tested for misconfig
Cryptographic Failures (Weak Hashing)A02 — #2CriticalLegacy systems still use MD5/SHA-1

Mapping auth pitfall categories to OWASP Top 10 (2021)

SECTION 6

Worked Example — Identifying Auth Pitfalls in a Code Review

Consider a simplified e-commerce web application. During a security code review, you encounter the following API endpoint and must identify every authentication and authorization pitfall present. This example walks through a systematic analysis using the taxonomy from Section 5.

📝

Vulnerable Code Snippet (Pseudocode)

// POST /api/login function login(req, res) { user = db.query("SELECT * FROM users WHERE email='" + req.body.email + "'") if (user.password == req.body.password) { session_id = "sess_" + user.id + "_" + Date.now() res.cookie("session", session_id) return res.json({success: true}) } } // GET /api/orders/:id function getOrder(req, res) { order = db.query("SELECT * FROM orders WHERE id=" + req.params.id) return res.json(order) }

Systematic Auth Pitfall Analysis

  1. 1

    Step 1 — Examine Credential Validation

    The login function compares user.password == req.body.password in plaintext. This reveals two critical pitfalls: the password is stored in plaintext in the database (CWE-256), and the comparison uses a simple equality operator rather than a constant-time comparison function, introducing a timing side-channel that allows attackers to infer password characters based on response time differences.
    Pitfalls found: Plaintext password storage, timing side-channel, SQL injection in email field
  2. 2

    Step 2 — Examine Rate Limiting

    There is no rate limiting, account lockout mechanism, or CAPTCHA on the login endpoint. An attacker can send unlimited login requests, making brute-force and credential stuffing attacks trivially feasible.
    Pitfall found: Missing rate limiting (CWE-307)
  3. 3

    Step 3 — Examine Session Token Generation

    The session ID is constructed as "sess_" + user.id + "_" + Date.now(). This token is entirely predictable: the user ID is a small integer and Date.now() returns a millisecond timestamp that can be narrowed to a small window. An attacker who knows a user's ID can enumerate valid session tokens. The entropy of this scheme is effectively near zero compared to the 128-bit minimum recommended by OWASP.
    Pitfall found: Predictable session token (CWE-330)
  4. 4

    Step 4 — Examine Cookie Security Attributes

    The cookie is set with res.cookie("session", session_id) — no HttpOnly, Secure, or SameSite flags. Without HttpOnly, JavaScript (and therefore XSS payloads) can read the cookie. Without Secure, the cookie will be transmitted over unencrypted HTTP. Without SameSite, CSRF attacks can leverage the authenticated session.
    Pitfalls found: Missing HttpOnly (CWE-1004), missing Secure flag (CWE-614), CSRF exposure
  5. 5

    Step 5 — Examine Authorization on /api/orders/:id

    The getOrder endpoint retrieves an order by its ID from the URL parameter without verifying that the currently authenticated user owns that order. By simply changing the :id parameter, any authenticated user can access any order in the system. This is a textbook Insecure Direct Object Reference (IDOR) vulnerability enabling horizontal privilege escalation.
    Pitfall found: IDOR / Missing authorization check (CWE-639)
📋

TOTAL PITFALL COUNT

This short code snippet contains at least eight distinct auth pitfalls: plaintext password storage, timing side-channel, SQL injection, missing rate limiting, predictable session tokens, missing HttpOnly/Secure cookie flags, CSRF vulnerability, and an IDOR. In practice, a single vulnerable endpoint can serve as a gateway to full database compromise. This demonstrates why systematic code review against a pitfall taxonomy is indispensable.

SECTION 7

Pitfalls vs. Mitigations — A Comparison

Knowing the pitfalls is necessary but insufficient — security practitioners must also know the standard mitigations for each vulnerability class. The table below pairs each major pitfall with its recommended countermeasure, providing a practical reference for secure design.

Auth PitfallRecommended MitigationImplementation Notes
Plaintext / weak password hashingUse bcrypt, scrypt, or Argon2idAdaptive cost factor; bcrypt work factor ≥ 12; Argon2id with ≥ 64 MB memory
Brute-force / credential stuffingRate limiting + account lockout + MFAProgressive delays; lockout after N failures; TOTP or WebAuthn as second factor
Predictable session tokensCSPRNG with ≥ 128 bits entropyUse framework-provided session managers (e.g., express-session with secure store)
Session fixationRegenerate session ID on loginInvalidate old session; bind new session to user identity
Missing cookie security flagsSet HttpOnly, Secure, SameSite=StrictHttpOnly blocks JS access; Secure enforces HTTPS; SameSite prevents CSRF
IDOR / missing authorizationServer-side ownership check on every requestQuery: WHERE id = :id AND user_id = :authenticated_user_id; use UUIDs over sequential IDs
Privilege escalationRole-based access control (RBAC) middlewareCentralized policy enforcement point; deny by default; audit all role assignments
JWT tampering (e.g., alg=none)Validate algorithm server-side; use asymmetric signingWhitelist accepted algorithms; never trust the token's 'alg' header alone

Auth Pitfalls and Their Standard Mitigations

✦

KEY TAKEAWAY

Security mitigations should not be invented ad hoc. Just as civil engineers follow established building codes rather than improvising structural designs, software engineers should rely on well-vetted libraries and frameworks for authentication and session management. Rolling your own crypto or auth system is the software equivalent of designing your own bridge without a civil engineering degree — the consequences of a subtle error can be catastrophic and may not manifest until the system is under real load (or real attack).

SECTION 8

Connection to Advanced Security Concepts

The authentication and authorization pitfalls examined in this lesson are foundational, but the field of web application security extends into increasingly sophisticated territory. Modern architectures — microservices, serverless functions, single-page applications with OAuth 2.0 / OpenID Connect flows, and API gateways — introduce new variants of the same conceptual errors. Understanding the basics prepares you to reason about these more complex scenarios.

Foundational ConceptAdvanced Extension
Session cookies for state managementOAuth 2.0 access tokens, refresh tokens, and token introspection endpoints. Pitfalls include token leakage via URL fragments, implicit grant misuse, and insufficient scope validation.
Server-side role checks (RBAC)Attribute-Based Access Control (ABAC) and policy engines (e.g., OPA/Rego). Pitfalls include policy drift, overly permissive defaults, and failure to propagate context in distributed call chains.
Password-based authenticationPasswordless authentication via WebAuthn/FIDO2, passkeys, and hardware security keys. Eliminates credential stuffing entirely but introduces pitfalls around key attestation and account recovery.
IDOR on monolithic endpointsBroken Object-Level Authorization (BOLA) in REST/GraphQL APIs — OWASP API Security Top 10. GraphQL introspection queries can reveal schema details that facilitate targeted BOLA attacks.
Predictable session tokensJWT vulnerabilities: algorithm confusion (RS256 → HS256), 'none' algorithm bypass, kid injection, and JWK Set URL manipulation. Advanced token-based auth introduces an entire class of cryptographic pitfalls.

From Foundational Auth Pitfalls to Advanced Security Topics

As you progress in application security, you will encounter formal methods for modeling access control (such as the Bell-LaPadula model for confidentiality and the Biba model for integrity), automated static analysis tools that detect auth pitfalls in code, and runtime application self-protection (RASP) systems that enforce security policies at the middleware layer. The conceptual taxonomy built in this lesson — distinguishing authentication, session management, and authorization — remains the organizing framework regardless of the complexity of the architecture.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

A developer argues that their web application is secure because the 'Admin Panel' link is only rendered in the HTML for users with the admin role. No server-side role check exists on the /admin/* routes. Explain why this is insufficient and classify the specific auth pitfall category.
Show answer
Hiding a UI element is a presentation-layer concern, not a security control. An attacker can simply type the admin URL directly into their browser, use a tool like cURL, or inspect the client-side JavaScript to discover hidden routes. This constitutes a broken access control vulnerability, specifically a vertical privilege escalation (CWE-862: Missing Authorization). The correct mitigation is server-side middleware that verifies the authenticated user's role on every request to a protected endpoint, following the principle that all authorization decisions must be enforced on the server. This aligns with OWASP A01: Broken Access Control.

Question 2: BASIC CALCULATION

A web application generates session tokens using a 16-character alphanumeric string (characters a–z, A–Z, 0–9). Calculate the entropy of this token in bits. Does it meet the OWASP recommendation of ≥ 128 bits?
Show answer
The character set cardinality C = 26 + 26 + 10 = 62. With a token length of 16, the total number of possible tokens N = 62¹⁶. The entropy H = log₂(62¹⁶) = 16 × log₂(62) ≈ 16 × 5.954 ≈ 95.3 bits. This falls significantly short of the OWASP-recommended 128 bits. To achieve 128 bits of entropy with the same character set, the required length would be l = ⌈128 / log₂(62)⌉ = ⌈128 / 5.954⌉ = ⌈21.5⌉ = 22 characters. Alternatively, switching to a 32-character hexadecimal token (C = 16, l = 32) yields exactly 128 bits.

Question 3: INTERMEDIATE

An API endpoint GET /api/users/:userId/profile returns the profile data for the given userId. The application uses JWT tokens for authentication. A penetration tester discovers that by changing the :userId parameter in the URL while using their own valid JWT, they can retrieve other users' profiles. Identify the vulnerability, explain why the JWT alone does not prevent it, and propose a concrete fix.
Show answer
This is an Insecure Direct Object Reference (IDOR) vulnerability — a subcategory of broken access control (CWE-639). The JWT establishes authentication (it proves who the caller is), but it does not inherently enforce authorization (whether the caller is permitted to access a specific resource). The server must extract the authenticated user's identity from the JWT and compare it against the requested userId. A concrete fix involves modifying the query logic to either (a) use the userId from the JWT claims instead of from the URL path, e.g., const userId = jwt.sub;, or (b) add a server-side check: if (req.params.userId !== jwt.sub) return 403;. This must be enforced in middleware to prevent individual developers from forgetting the check.

Question 4: APPLIED

You are designing the authentication system for an online banking application. The product manager requests that the 'Remember Me' feature keep users logged in for 30 days. Identify at least three authentication/session management pitfalls that could arise from this requirement and describe how you would architect the feature to mitigate each one.
Show answer
Three key pitfalls: (1) Session token theft via long-lived cookies — a 30-day cookie massively extends the window during which a stolen token remains valid. Mitigation: use a short-lived access token (e.g., 15 minutes) paired with a long-lived refresh token stored in a secure, HttpOnly cookie. The refresh token should be rotated on each use and bound to the device fingerprint or IP range. (2) Session persistence after password change — if a user changes their password (possibly because they suspect compromise), all existing sessions including 'remember me' tokens must be invalidated. Implement a per-user token generation counter that increments on password change. (3) Sensitive actions without re-authentication — a remembered session should not grant access to high-risk operations (e.g., wire transfers, changing the email address) without step-up authentication. Implement a 'last active authentication' timestamp and require re-entry of credentials or MFA for sensitive actions if the last interactive login exceeds a threshold (e.g., 5 minutes).

Question 5: CRITICAL THINKING

A microservices architecture uses JWTs passed between services for inter-service authorization. Service A issues a JWT with claims {"sub": "user123", "role": "admin", "scope": "service-b"}. Service B trusts this JWT and grants admin access. Analyze the trust model: what happens if Service A is compromised? How does this differ from a centralized authorization server model, and what additional pitfalls does the distributed approach introduce? Propose an architectural improvement.
Show answer
If Service A is compromised, the attacker can forge JWTs with arbitrary claims — including elevated roles and scopes — because Service A holds the signing key (or has access to the shared secret). Service B, trusting any validly signed token, will honor these forged claims. This creates a transitive trust vulnerability: the compromise of one service cascades to all services that trust its tokens. In contrast, a centralized authorization server (e.g., an OAuth 2.0 authorization server) issues tokens using a key that individual services never possess, so compromising Service A does not grant token-forging capability. Additional pitfalls in the distributed model include: (a) token scope inflation — Service A may issue tokens with broader scopes than necessary; (b) inability to revoke tokens — JWTs are stateless, so a compromised token remains valid until expiration; (c) algorithm confusion if different services expect different signing algorithms. Architectural improvement: adopt a centralized identity provider (IdP) with asymmetric signing (RS256). Services validate tokens using the public key but cannot sign new ones. Implement short token lifetimes (≤ 5 min), token introspection for sensitive operations, and audience (aud) claim validation so tokens intended for Service B cannot be replayed against Service C.

SUMMARY

Lesson Summary

Summary

Web application authentication and authorization pitfalls remain among the most exploited vulnerability classes in software, with Broken Access Control ranking as the #1 risk in the OWASP Top 10 (2021). The pitfalls span three interrelated domains: authentication failures (plaintext storage, weak hashing, missing rate limiting, credential stuffing), session management weaknesses (predictable tokens, session fixation, missing cookie security flags, insufficient entropy), and authorization flaws (IDOR, vertical and horizontal privilege escalation, client-side-only enforcement). Each pitfall arises from a violation of core security principles: the principle of least privilege, defense in depth, and the imperative that all security decisions be enforced server-side.

Standard mitigations include using adaptive hashing algorithms (bcrypt, Argon2id), cryptographically secure random session tokens with ≥ 128 bits of entropy, multi-factor authentication, server-side ownership validation on every resource access, and centralized authorization middleware (RBAC/ABAC). The taxonomy of auth pitfalls — mapping to CWEs and OWASP categories — provides a systematic checklist for code review, penetration testing, and secure architecture design. As systems evolve toward microservices and API-first architectures, these foundational concepts extend directly into OAuth 2.0 flows, JWT security, and distributed trust models.

Varsity Tutors • Cyber Security • Web App Auth Pitfalls