Skip to content

Chapter 12: Authentication, Authorization, and Access Control

Modern security systems rest on three pillars: verifying who a user is, determining what they’re allowed to do, and recording what they did. This chapter examines each pillar along with the protocols and attacks surrounding them.

12.1 The AAA Framework

Definition 12.1 (Authentication, Authorization, and Accounting)

Authentication (AuthN) verifies the identity of a principal. Authorization (AuthZ) determines which resources and actions an authenticated principal may access. Accounting (Audit) records principal actions for forensic analysis and compliance.

Authentication factors fall into three categories:

Factor Type Examples
Something you know Knowledge Password, PIN, security question
Something you have Possession Hardware token, smart card, phone
Something you are Inherence Fingerprint, face, retina, voice

12.2 Password Authentication

12.2.1 Password Hashing: bcrypt and Argon2

Storing plaintext or MD5/SHA-1 passwords is a serious vulnerability. Modern systems use adaptive password hashing algorithms that are deliberately slow and memory-hard.

Definition 12.2 (Adaptive Password Hash)

An adaptive password hash function incorporates a cost factor that can be increased as hardware becomes faster, keeping brute-force attacks economically infeasible. It also incorporates a random salt to prevent precomputation (rainbow table) attacks.

Algorithm Memory-Hard Parallelism NIST Recommended
MD5 (legacy) No Yes No
bcrypt No No Acceptable
scrypt Yes Limited Acceptable
Argon2id Yes Configurable ✓

NIST SP 800-63B Password Guidance

NIST SP 800-63B (2024 revision) recommends: minimum 8-character passwords (64+ preferred); no mandatory periodic rotation unless compromise is suspected; check against breached-password lists (Have I Been Pwned corpus); no complexity rules that produce predictable substitutions (e.g., P@ssw0rd); allow all printable ASCII and Unicode characters.

12.2.2 Credential Stuffing

Credential Stuffing

Attackers use leaked username/password pairs from one breach to attack other services, exploiting password reuse. Defences include: breach monitoring (HaveIBeenPwned API), rate limiting, CAPTCHA, device fingerprinting, and multi-factor authentication.

12.3 Multi-Factor Authentication

12.3.1 TOTP: Time-Based One-Time Passwords

RFC 6238 defines TOTP as an extension of HOTP (RFC 4226) that uses the current Unix time rather than a counter. The shared secret and time window produce a short-lived code. The 30-second window exists to tolerate clock drift between the user’s device and the server—in practice most implementations also accept codes from the adjacent windows (valid_window=1) to handle users who generate a code just as the window expires. That tolerance creates a 60-second replay window, which is why servers should record the last accepted code and reject it if presented again within the same window.

\[\begin{align*} T &= \left\lfloor \frac{\text{Unix time}}{30} \right\rfloor \\ \text{HOTP}(K, T) &= \text{Truncate}\!\left(\text{HMAC-SHA1}(K, T)\right) \bmod 10^6 \end{align*}\]
import pyotp
import time

# Provision: share base32 secret with user (shown in QR code)
secret = 'JBSWY3DPEHPK3PXP'
totp = pyotp.TOTP(secret)

# Generate current code (valid for 30-second window)
current_code = totp.now()
print(f"Current OTP: {current_code}")

# Verify a user-supplied code (allows 1 window drift)
user_input = input("Enter OTP: ")
valid = totp.verify(user_input, valid_window=1)
print(f"Valid: {valid}")

# Provisioning URI for QR code generation
uri = totp.provisioning_uri(name='alice@example.com',
                            issuer_name='MyApp')
print(uri)

12.3.2 FIDO2 and WebAuthn

FIDO2 consists of the W3C WebAuthn API and the FIDO CTAP2 protocol. Credentials are public-key pairs where the private key never leaves the authenticator. Authentication proves possession of the private key via a challenge-response signature.

WebAuthn Advantages

WebAuthn credentials are origin-bound: the relying party ID is cryptographically bound to the credential, making phishing attacks that use lookalike domains ineffective. Passkeys extend WebAuthn by syncing credentials across devices via cloud keychain.

TOTP codes are fundamentally phishable: nothing stops a real-time phishing proxy from relaying the victim’s code to the legitimate site before it expires. Attacker-in-the-middle toolkits like Evilginx2 do exactly this, harvesting both the session cookie and the TOTP code in one automated flow. FIDO2/WebAuthn is the only widely deployed MFA mechanism that is phishing-resistant by design—the origin binding means a credential registered at bank.example simply can’t be used at bank-secure.attacker.example.

SIM-swapping is the other dominant attack on TOTP and SMS-based MFA. An attacker calls the victim’s mobile carrier, impersonates the victim (often with data from previous breaches or social engineering), and convinces the carrier to port the number to a new SIM the attacker controls. From that point the attacker receives all SMS codes and TOTP is not involved at all. High-profile SIM-swap attacks have hit Twitter’s internal tooling (2020), cryptocurrency exchange accounts, and even journalists. FIDO2 hardware tokens are immune to SIM-swapping because they don’t involve telephony. For TOTP, the only mitigations are carrier-level port freeze requests and pushing users toward hardware tokens instead of authenticator apps.

12.4 OAuth 2.0 and OpenID Connect

12.4.1 OAuth 2.0 Authorization Code Flow

OAuth 2.0 (RFC 6749) delegates authorization—not authentication—to an Authorization Server. The Authorization Code flow is the recommended pattern for confidential clients. The word “authorization” is load-bearing here: OAuth tells you what a user has granted permission to do, not who that user is. Using an access token to determine identity is a common mistake that leads to account takeover when tokens are issued to multiple clients—OIDC’s ID token is the correct mechanism for identity assertions.

image

12.4.2 PKCE: Proof Key for Code Exchange

PKCE (RFC 7636) prevents authorization code interception attacks in public clients (mobile apps, SPAs). The client generates a code_verifier (random 43–128 chars), computes code_challenge = BASE64URL(SHA-256(code_verifier)), and sends the challenge in the authorization request. The token endpoint then verifies the verifier.

The intuition behind PKCE is straightforward: an attacker who intercepts the authorization code (via a malicious app registered on the same custom URI scheme, or via a compromised redirect URI) can’t exchange it for a token without also knowing the code_verifier that was generated in the same session on the legitimate device. The verifier never travels in the redirect, so intercepting the redirect is useless. PKCE was originally designed for public clients that can’t hold a client secret securely, but RFC 9700 recommends it for all clients including confidential server-side apps. Even when a client secret exists, PKCE adds a second factor specific to that authorization request, preventing code injection attacks where an attacker tricks the server into accepting a stolen code mid-flow.

Implicit Flow Deprecated

The OAuth 2.0 Implicit flow (response_type=token) is deprecated per RFC 9700. Access tokens in URL fragments are exposed in browser history and referrer headers. All new deployments must use Authorization Code with PKCE.

The implicit flow’s fundamental flaw isn’t just history and referrer leakage—it’s that access tokens appear in URLs, which means they end up in server access logs, browser history sync, and any browser extension that can read URLs. These tokens have no code verifier binding, so anyone who captures the token from any of those sources gets full access. The flow was designed for browser-based apps that couldn’t do a back-channel token request in the pre-CORS era; that constraint no longer exists, removing the only rationale for its use.

12.4.3 OpenID Connect and JWT Structure

OpenID Connect (OIDC) adds an ID token (a signed JWT) on top of OAuth 2.0, enabling authentication. A JWT has three Base64URL-encoded parts separated by dots:

\[\underbrace{\texttt{eyJhbGciOiJSUzI1NiJ9}}_{\text{Header}} \texttt{.} \underbrace{\texttt{eyJzdWIiOiJ1c2VyMTIzIn0}}_{\text{Payload (claims)}} \texttt{.} \underbrace{\texttt{<signature>}}_{\text{Signature}}\]

Standard OIDC claims include sub (subject), iss (issuer), aud (audience), exp (expiry), iat (issued-at), and nonce.

12.5 JWT Attacks

Algorithm Confusion: alg=none and RS256 \(\to\) HS256

alg=none: Some libraries accept JWTs with "alg":"none" and no signature, treating them as valid. Defence: reject tokens where alg is not in an explicit allowlist.

RS256 \(\to\) HS256: If the server uses the RSA public key as the HMAC secret when alg=HS256 is supplied, an attacker can forge tokens using the (public) key. Defence: pin the expected algorithm server-side; never derive the verification key from the token header.

The RS256\(\to\)HS256 confusion attack deserves more detail because it surprises even experienced developers. In RS256, the server signs with an RSA private key and verifies with the public key—and the public key is, by definition, public. A vulnerable JWT library selects the verification algorithm from the token’s own alg header. An attacker changes that header to HS256, then signs the token with the server’s RSA public key (which the attacker has). When the vulnerable library verifies, it reads alg=HS256 and computes HMAC-SHA256(token, publicKey), which matches exactly—so verification succeeds. The attacker has produced a token claiming any identity they want. The fix is one line: algorithms=[’RS256’] passed to the decode call. Never let the token header dictate which algorithm you use; that field is attacker-controlled.

The alg:none attack exploits a misguided feature in early JWT specifications that allowed unsigned tokens for internal messaging. Some libraries implemented it as a valid algorithm value, meaning a token with "alg":"none" and an empty signature field passes “verification.” Real-world exploits of both attacks appeared in Auth0’s legacy sdk, the python-jose library, and numerous custom JWT implementations. Check your library’s changelog for CVEs mentioning “algorithm confusion” before trusting it in production.

kid Injection

The JWT kid (key ID) header parameter may be used to look up a key in a database. If unsanitised, an attacker can inject SQL: "kid":"’ UNION SELECT ’attacker_key’ --". Defence: validate kid against a strict allowlist; use parameterised queries.

12.6 SAML and XML Attacks

Definition 12.3 (SAML Assertion)

Security Assertion Markup Language (SAML) 2.0 uses XML documents called assertions signed by an Identity Provider (IdP) to convey authentication and attribute statements to a Service Provider (SP).

XML Signature Wrapping (XSW)

XSW attacks exploit the gap between which element is signed and which is processed. An attacker duplicates the signed element, injects a malicious clone elsewhere in the XML tree, and tricks the SP into processing the unsigned clone while the signature validates over the legitimate copy. Mitigation: validate that the signed element is the one actually consumed; use strict XML canonicalisation.

12.7 Access Control Models

Definition 12.4 (RBAC, ABAC, and ReBAC)

Role-Based Access Control (RBAC): permissions assigned to roles; users assigned to roles. Simple and auditable but coarse-grained. Attribute-Based Access Control (ABAC): policies evaluate subject, resource, and environment attributes. Expressive but complex. Relationship-Based Access Control (ReBAC): access determined by graph relationships between users and objects (e.g., Google Zanzibar, “user X owns document Y”).

12.7.1 Privilege Escalation

Definition 12.5 (Privilege Escalation)

Vertical privilege escalation: a lower-privileged user gains higher-privileged capabilities (e.g., a regular user becomes an admin). Horizontal privilege escalation: a user accesses resources belonging to another user of the same privilege level (also called IDOR — Insecure Direct Object Reference).

12.8 Broken Access Control and IDOR

Broken Access Control is the OWASP Top 10 #1 vulnerability (2021–2025). A classic form is IDOR:

from flask import Flask, request, jsonify, g

app = Flask(__name__)

# VULNERABLE: no ownership check
@app.route('/api/invoice/<int:invoice_id>')
def get_invoice_bad(invoice_id):
    invoice = db.query('SELECT * FROM invoices WHERE id = ?',
                       invoice_id)
    return jsonify(invoice)   # Any user can fetch any invoice!

# SECURE: verify authenticated user owns the resource
@app.route('/api/invoice/<int:invoice_id>')
def get_invoice_good(invoice_id):
    user_id = g.current_user['id']
    invoice = db.query(
        'SELECT * FROM invoices WHERE id = ? AND owner_id = ?',
        invoice_id, user_id)
    if not invoice:
        return jsonify({'error': 'Not found'}), 404
    return jsonify(invoice)

12.9 Session Management

Secure Cookie Attributes

  • HttpOnly — prevents JavaScript access; mitigates XSS-based session theft.

  • Secure — cookie transmitted only over HTTPS.

  • SameSite=Strict — cookie not sent on cross-site requests; prevents CSRF.

  • __Host- prefix — cookie scoped to the exact host, no subdomains.

Session Fixation

An attacker sets a known session ID on the victim’s browser (e.g., via URL parameter or cross-subdomain cookie), then waits for the victim to authenticate. The server elevates the fixed session, giving the attacker an authenticated session. Defence: regenerate the session ID on every privilege change, including login.

Session fixation and session hijacking are often confused but differ in when the attacker acquires the session token. In hijacking, the attacker steals a session that is already authenticated—typically via XSS, network sniffing on HTTP, or a predictable session ID. In fixation, the attacker plants a known session ID before authentication; they don’t need to steal anything because they already know the value. The defence for hijacking is making tokens hard to steal (HttpOnly, Secure, short lifetime, binding to IP or User-Agent). The defence for fixation is simpler and more reliable: always issue a brand-new session ID the moment the authentication state changes. Flask’s session.regenerate(), Django’s request.session.cycle_key(), and Spring Security’s sessionFixation().newSession() all do this. Most modern frameworks do it automatically, but custom session implementations frequently forget it.

Session hijacking remains relevant even with HttpOnly cookies because XSS can make authenticated requests in the context of the victim’s session without needing to read the cookie. Attackers exfiltrate data or perform actions—they don’t need the token string itself. This is why XSS mitigation (CSP, output encoding) and session security are complementary layers, not alternatives.

12.10 Zero Trust Identity

Definition 12.6 (Zero Trust)

Zero Trust (NIST SP 800-207) assumes no implicit trust based on network location. Every access request is evaluated against identity, device posture, and context continuously, not just at login. The principle: “never trust, always verify.”

Key Zero Trust controls include continuous risk scoring, device health attestation (via TPM or MDM), just-in-time privilege, and microsegmentation of workloads.

12.11 Exercises

Exercise 12.1

Implement a Python TOTP provisioning and verification service. Your implementation must: (a) generate a random base32 secret and return a QR-code URI; (b) verify a supplied 6-digit code with a \(\pm 1\) window tolerance; (c) enforce rate limiting so that no more than 5 verification attempts are allowed per 30-second window. Explain how the time window tolerance creates a replay window and how to minimise it.

Exercise 12.2

Analyse the OAuth 2.0 authorization code flow threat model. For each of the following adversary capabilities, state whether the flow is vulnerable with and without PKCE, and explain the mechanism of attack or defence: (a) attacker can intercept the redirect URI on a mobile device; (b) attacker controls a malicious app registered on the same custom URI scheme; (c) attacker can read the victim’s browser history.

Exercise 12.3

A web application exposes GET /api/ users/ {id}/ documents. An authenticated user with ID 42 discovers they can access documents for user ID 43 by modifying the path. (a) Classify this vulnerability. (b) Write a Flask route that correctly prevents this. (c) Describe how automated IDOR scanning tools detect such endpoints.

Exercise 12.4

Explain the JWT RS256\(\to\)HS256 algorithm confusion attack in detail. Include: (a) the attacker’s step-by-step procedure to forge a token; (b) why the server accepts the forged token in the vulnerable case; (c) two distinct code-level defences a JWT library should implement.

Exercise 12.5

A security engineer wants to enforce MFA for all administrative actions but allow password-only for read operations. Design an ABAC policy schema (as JSON or pseudocode) that expresses this requirement. Your schema should include subject attributes, resource attributes, and environment attributes (e.g., mfa_verified, action, resource_sensitivity).

Exercise 12.6

Describe the XML Signature Wrapping attack against a SAML Service Provider. Draw a simplified XML tree before and after the attack, indicating which element is signed and which element the vulnerable SP processes. Propose a concrete mitigation at the XML parsing layer.