Identity, Security and Privacy EngineeringIntroduction and ContextModern web applications are not merely collections of pages and APIs. They are socio-technical systems that process identities, permissions, financial information, health data, intellectual property and operational decisions. Consequently, security and privacy must be engineered as system properties rather than added as a final testing activity. Identity, security and privacy engineering addresses three related questions: 1. Who or what is interacting with the system? This is the identity problem. 2. What is that subject allowed to do? This is the authorization problem. 3. How can the system remain trustworthy despite attack, error, misuse and regulatory constraints? This is the security and privacy problem. A robust design combines threat modelling, secure coding, strong authentication, explicit authorization, protected sessions and tokens, cryptography, secret management, software supply-chain controls, privacy engineering and incident response. These controls operate across the full lifecycle: requirements, architecture, implementation, deployment, operation and retirement. Security objectives are commonly expressed through the CIA triad: - Confidentiality: preventing unauthorized disclosure.
- Integrity: preventing unauthorized or undetected alteration.
- Availability: ensuring reliable access for authorized users.
Identity systems add accountability, authentication and non-repudiation, although non-repudiation normally requires carefully managed cryptographic and legal controls rather than authentication alone. Privacy extends beyond confidentiality: a system may keep data secret while still collecting excessive information, retaining it too long or using it for an unexpected purpose. Learning ObjectivesBy the end of this chapter, learners should be able to: - model threats using assets, trust boundaries, attack surfaces and adversarial techniques;
- apply secure coding practices to common OWASP risks;
- distinguish identification, authentication, authorization and accounting;
- design secure sessions and evaluate cookies, tokens, OAuth 2.0 and OpenID Connect;
- apply zero-trust principles to web and API architectures;
- select appropriate encryption, hashing, key-management and secret-management controls;
- assess software supply-chain and dependency risks;
- incorporate privacy by design and regulatory accountability;
- plan detection, response, recovery and post-incident learning.
1. Security Foundations and Threat Modelling1.1 Identity conceptsIdentification is a claim of identity, such as a username or email address. Authentication verifies that claim using one or more factors: - knowledge: password or PIN;
- possession: hardware security key or authenticator device;
- inherence: biometric characteristic;
- contextual or adaptive evidence: device, location or behavioural signals.
Multi-factor authentication requires independent factors. Two passwords are generally not two-factor authentication because both are knowledge factors. Phishing-resistant methods, particularly WebAuthn and FIDO2 security keys or platform authenticators, bind authentication to the legitimate relying-party origin and are therefore stronger than reusable passwords or one-time codes against phishing. Authorization determines whether an authenticated subject may perform an action on a resource. Accounting records relevant security events for audit, detection and investigation. These concepts must not be conflated: a valid login does not imply permission to access every record. 1.2 Assets, threats and vulnerabilitiesAn asset is something valuable, including personal data, credentials, payment instructions, source code, availability or organizational reputation. A threat is a potential cause of harm. A vulnerability is a weakness that can be exploited. Risk combines the likelihood and impact of an adverse event; although organizations often use qualitative scales, the result should not be treated as a scientifically precise probability unless reliable data supports that interpretation. Threat modelling is a structured way to discover and prioritize security requirements before implementation. A practical process is: 1. Define system purpose, users, dependencies and security objectives. 2. Draw data-flow diagrams showing processes, data stores, external entities and trust boundaries. 3. Inventory assets and classify data by sensitivity and regulatory significance. 4. Identify threats using STRIDE, attack trees, abuse cases, or relevant threat-intelligence frameworks. 5. Estimate impact and likelihood using an explicit organizational method. 6. Select mitigations, owners and verification tests. 7. Revisit the model when architecture, dependencies or business use changes. STRIDE provides a useful mnemonic: Spoofing identity, Tampering, Repudiation, Information disclosure, Denial of service and Elevation of privilege. It is a discovery aid, not a complete risk methodology. Attack trees start with an attacker goal and decompose it into alternative or combined subgoals. The MITRE ATT&CK knowledge base can help relate observed adversary techniques to defensive controls, but it should not replace application-specific analysis. 1.3 Trust boundaries and attack surfacesA trust boundary separates components with different assumptions or authorities. Examples include a browser-to-server boundary, a public API-to-internal service boundary, a tenant boundary and a CI/CD system-to-production boundary. Every crossing should trigger validation, authentication where appropriate, authorization, logging and careful data handling. The attack surface includes internet-facing endpoints, browser code, APIs, administrative interfaces, identity providers, dependencies, build pipelines, cloud permissions, error channels and human workflows. Reducing attack surface is frequently more effective than attempting to make every exposed component perfectly secure. 2. Secure Architecture and Zero TrustZero trust is an architectural and governance approach summarized by never trust, always verify. It does not mean that every request must use the same authentication mechanism or that internal networks are inherently hostile. It means that network location alone is insufficient evidence of trust. A zero-trust web architecture commonly applies the following principles: - authenticate users, services and devices according to risk;
- authorize every request using identity, resource, action, context and policy;
- use least privilege and short-lived credentials;
- segment services and limit east-west movement;
- assume breach and design for containment;
- continuously monitor, evaluate and improve controls.
For example, a request to download a payroll report may be evaluated against user identity, role, department, tenant, device posture, time, purpose and recent risk signals. Authorization should be enforced at the server and preferably close to the resource, not only by hiding a button in a user interface. A policy decision point evaluates policy, while a policy enforcement point blocks or permits the operation. Central policy services can improve consistency, but excessive centralization can create an availability dependency and a difficult-to-audit policy language. Policies should be versioned, tested with positive and negative cases, and reviewed by both security and domain owners. 3. OWASP Risks and Secure CodingThe OWASP Top 10 is an awareness and prioritization resource rather than a complete security standard. Important web risks include: Broken access controlTypical failures include insecure direct object references, missing ownership checks, privilege escalation and tenant-isolation defects. Every sensitive operation should check both the requested action and the subject's relationship to the specific resource. A server must not rely on identifiers being unpredictable; authorization is still required if an identifier is a UUID. InjectionSQL, command, template, LDAP and expression-language injection occurs when untrusted data changes the structure of an interpreted command. Parameterized queries separate code from data. Allow-list validation is preferable for constrained values such as sort fields, while output encoding must be appropriate to the destination context: HTML, attribute, JavaScript, CSS, URL and SQL contexts differ. Cross-site scripting and request forgeryCross-site scripting (XSS) allows attacker-controlled script to execute in a victim's browser. Context-sensitive output encoding, safe templating, input constraints, Content Security Policy and avoiding dangerous DOM APIs reduce risk. Content Security Policy is a defense in depth control, not a replacement for correct encoding. Cross-site request forgery (CSRF) abuses a browser's automatic inclusion of credentials. SameSite cookies, origin checking and anti-CSRF tokens are useful controls, especially for cookie-authenticated state-changing requests. APIs using an Authorization header with a non-automatically attached bearer token have a different CSRF profile, but remain exposed to token theft and other attacks. Cryptographic failuresSensitive data should be classified before deciding whether to encrypt, tokenize, hash or avoid collecting it. Passwords must be stored using a slow, memory-hard password hashing function such as Argon2id, with a unique salt per password and parameters selected through performance testing. Encryption is reversible with a key; hashing is designed to be one-way; encoding is not a security control. Insecure design and misconfigurationA secure implementation cannot repair an unsafe business process. Examples include unlimited password reset attempts, weak recovery procedures, unrestricted bulk export and failure to separate approval from execution. Secure defaults, infrastructure-as-code review, removal of development endpoints, restrictive CORS policy, controlled error messages and timely patching reduce misconfiguration risk. Identification, authentication and logging failuresControls should address credential stuffing, password spraying, session fixation, weak recovery, excessive login feedback and missing audit trails. Logs should support detection without exposing passwords, access tokens, encryption keys or unnecessary personal data. Time synchronization, correlation identifiers and protected log storage are essential for investigation. 4. Authentication, Authorization and Federation4.1 Passwords and account recoveryPasswords should be checked against breached-password lists, protected from online guessing through rate controls and monitored for suspicious patterns. Password composition rules should not encourage predictable substitutions or arbitrary frequent changes. Recovery is an authentication pathway and must receive controls equivalent to login. Security questions are weak because answers are often public or reusable. 4.2 Sessions and cookiesA server-side session usually stores state on the server and gives the browser a random session identifier. A secure session identifier should be generated by a cryptographically secure random generator, be sufficiently long, expire according to risk, and be rotated after login or privilege elevation to prevent session fixation. Important cookie attributes include: - Secure: send only over HTTPS;
- HttpOnly: prevent ordinary JavaScript access;
- SameSite: constrain cross-site sending;
- narrow Domain and Path scope;
- appropriate expiration and deletion behavior.
HttpOnly does not prevent an attacker who can execute script from performing actions through the victim's browser. Session invalidation should occur at logout, credential compromise, account disablement and, for high-risk applications, relevant privilege or device changes. A distributed system must ensure that revocation and expiration are consistently enforced across nodes. 4.3 Tokens and JWT considerationsA bearer token grants access to whoever possesses it. Access tokens should therefore be short-lived, narrowly scoped and transmitted only over authenticated encrypted channels. Refresh tokens require stronger protection, rotation or sender-constraining where feasible, and revocation mechanisms. JSON Web Tokens (JWTs) are signed claims containers, not automatically encrypted containers. The consumer must validate the signature using a trusted key, issuer, audience, expiration, not-before and relevant scopes. It must also restrict accepted algorithms through configuration and key policy rather than trusting an algorithm value supplied by an attacker. JWTs are useful when independently verifiable claims and limited coupling are required, but server-side sessions may be simpler when immediate revocation and small payloads matter. A token should not contain unnecessary personal data because copies may persist in logs, browser storage, proxies or monitoring systems. 4.4 OAuth 2.0 and OpenID ConnectOAuth 2.0 is an authorization framework for delegated access; it is not, by itself, a login protocol. The authorization code flow with PKCE is the preferred pattern for public clients and is also valuable for confidential clients. PKCE binds the authorization request to the later token exchange through a code verifier and challenge, reducing authorization-code interception risk. The main roles are resource owner, client, authorization server and resource server. The client requests a defined scope, the resource owner grants it, and the authorization server issues an authorization code or token. Redirect URIs must be exact and pre-registered; open redirects and overly broad URI matching can enable token theft. OpenID Connect (OIDC) adds an identity layer to OAuth 2.0. An ID token communicates authentication information to the client, while an access token is intended for a resource server. The client must validate OIDC issuer, audience, signature, nonce and time claims according to the protocol and provider configuration. It must not use an access token as if it were an ID token. Federation reduces password duplication but introduces dependency on provider availability, configuration, key rotation, claims mapping and account-linking decisions. Automatic account linking based only on an email address can create account-takeover risk if verification and assurance are inadequate. 5. Cryptography, Secrets and Key ManagementCryptography should be selected from well-reviewed, maintained libraries and established protocols. TLS protects data in transit when correctly configured and when endpoint identities are validated. Modern authenticated encryption, such as AES-GCM or ChaCha20-Poly1305, provides confidentiality and integrity; nonce requirements must be obeyed. Reusing a nonce with the same key in schemes such as GCM can seriously compromise security. Key management is often more important than algorithm selection. Keys should have defined owners, purpose, creation and rotation procedures, access controls, backup policy, destruction policy and audit records. Key-encryption keys and data-encryption keys may be separated to reduce exposure. Rotation does not automatically protect historical data unless old ciphertext is re-encrypted or old keys are securely retained for authorized decryption. Secrets include API keys, database credentials, signing keys, certificates and cloud tokens. They should not be committed to source control, embedded in client-side code or printed in logs. A managed secret vault, workload identity, short-lived credentials, automated rotation and least-privilege access are preferable. Secret scanning is useful but cannot reliably remove a secret already exposed; exposed credentials should be revoked and replaced. 6. Software Supply-Chain SecurityWeb applications inherit risk from package registries, open-source libraries, build tools, container images, plugins and CI/CD platforms. Supply-chain security should include: - dependency inventories and a software bill of materials (SBOM);
- pinned or otherwise controlled versions with verified integrity;
- vulnerability and license review;
- minimal build permissions and isolated runners;
- protected branches, signed commits or artifacts where appropriate;
- reproducible or attestable builds;
- review of transitive dependencies and abandoned packages;
- staged deployment, rollback and runtime monitoring.
A vulnerability scanner produces findings, not risk decisions. Severity, exploitability, exposure, compensating controls and business impact must be considered. Updating every package immediately may introduce incompatibility; delaying all updates leaves known weaknesses exposed. Mature governance defines service-level expectations, exception ownership and evidence of remediation. 7. Privacy Engineering and GovernancePrivacy engineering translates principles into system properties. Common principles include purpose limitation, data minimization, accuracy, storage limitation, transparency, confidentiality and accountability. Privacy by design means these properties are considered before collection and remain testable throughout the lifecycle. Useful practices include: - maintain a data inventory and flow map;
- identify controller, processor and third-party responsibilities where applicable;
- define lawful purpose and retention periods;
- collect the minimum data needed for a specified function;
- separate identifiers from sensitive attributes through pseudonymization;
- provide access, correction, deletion and portability mechanisms where required;
- conduct privacy impact assessments for high-risk processing;
- restrict secondary use and measure re-identification risk;
- design deletion workflows that include backups, replicas and derived datasets.
Pseudonymization reduces direct identification but is not anonymization if re-identification remains reasonably possible. Encryption protects data but does not eliminate obligations concerning collection, purpose or retention. Privacy regulations vary by jurisdiction, sector and organizational role; technical teams should work with legal and compliance specialists rather than treating one regulation as universally applicable. Privacy also concerns fairness and power. A fraud model may reduce financial loss yet disproportionately challenge legitimate users. Data-driven security systems should document data sources, performance across relevant populations, human review paths, appeal mechanisms and retention of decisions. AI systems introduce additional risks such as prompt injection, sensitive-data leakage, model inversion and insecure tool use; they require explicit data boundaries, output validation and access controls. 8. Incident Response and ResilienceSecurity cannot be guaranteed by prevention alone. An incident capability normally includes preparation, detection and analysis, containment, eradication, recovery and lessons learned. Preparation includes roles, communication channels, evidence handling, legal contacts, backups, playbooks and exercises. Detection depends on useful telemetry: authentication anomalies, authorization failures, privilege changes, suspicious exports, dependency alerts, integrity changes and unusual service behavior. Alert quality matters; excessive false positives cause fatigue, while missing context prevents triage. Logs should be append-protected where possible, access-controlled, time-synchronized and retained according to operational and privacy requirements. Containment may involve disabling credentials, isolating workloads, blocking indicators or restricting functionality. Investigators should preserve evidence and avoid destroying volatile information without a considered plan. Recovery requires eradication of persistence, credential rotation, secure restoration, validation and close monitoring. Notification duties depend on jurisdiction, sector, contractual terms and the nature of affected data. Post-incident review should ask which assumptions failed, why controls did not prevent or detect the event, whether response time was adequate and which systemic changes are required. Blaming individuals without addressing design and governance weaknesses reduces learning. Applied Case: Illustrative Multi-Tenant Learning PlatformBackgroundA fictional university learning platform provides course content, assessment submission, instructor grading and analytics to multiple institutions. It uses OIDC login, a browser front end, REST APIs, cloud object storage and third-party analytics. ProblemA penetration test discovers that a student can alter an assignment identifier in an API request and download another student's submission. The platform also stores long-lived access tokens in browser local storage, includes student email addresses in analytics events and has a vulnerable image-processing dependency. AnalysisThe primary threat is broken object-level authorization across a tenant and student boundary. The token location increases the impact of XSS. Analytics represents a purpose and minimization issue. The dependency creates supply-chain and possibly remote-code-execution risk. These weaknesses interact: compromise of a browser session could expose data across authorization defects, while a dependency compromise could affect all institutions. Approach and solutionThe team creates a data-flow and trust-boundary model, identifies submissions and institutional records as high-value assets, and writes authorization rules requiring the authenticated subject to be an instructor with course membership or the owning student. Authorization is enforced in the service layer and tested with cross-tenant negative cases. Object identifiers remain untrusted. The team replaces long-lived browser-stored tokens with a protected session architecture and secure, appropriately scoped cookies. It deploys output encoding and a restrictive Content Security Policy, while retaining server-side authorization and CSRF protections. Analytics receives a pseudonymous event identifier rather than an email address, with documented retention and access controls. The image dependency is upgraded, the build is scanned, the SBOM is published internally, and the service is given a narrowly scoped workload identity. Existing tokens are revoked and audit logs are reviewed for possible access. OutcomeThe test suite now includes tenant-isolation, role, recovery, session and abuse cases. Security monitoring alerts on unusual bulk downloads and repeated authorization failures. A privacy review approves a reduced analytics design, and incident playbooks cover token compromise and dependency exploitation. Learning pointsThe case demonstrates that identity, authorization, privacy and supply-chain security are not separate checklists. A secure login cannot compensate for missing object-level authorization. Pseudonymization does not remove the need for governance. Defensive architecture requires both preventive controls and evidence that controls operate as intended. Challenges and LimitationsNo control is absolute. MFA can be bypassed through session theft, social engineering or weak recovery. Zero trust can become expensive and bureaucratic if policies are overly granular or telemetry is unreliable. Centralized identity creates concentration risk. Encryption can complicate search, analytics, recovery and lawful access. Privacy minimization may reduce data available for fraud investigation, while excessive collection increases exposure and governance burden. Automated scanners miss business-logic flaws, and AI-based detection may amplify bias or generate unmanageable alerts. Effective programs therefore use layered controls, explicit risk acceptance, continuous testing, threat-informed prioritization and executive accountability. Security metrics should emphasize meaningful outcomes—such as time to revoke exposed credentials, coverage of authorization tests, remediation of exploitable vulnerabilities and successful recovery exercises—rather than merely counting tools or vulnerabilities. Best-Practice Design Checklist- Model assets, trust boundaries, abuse cases and tenant boundaries early.
- Authenticate with phishing-resistant MFA for high-value access.
- Enforce authorization server-side for every sensitive action and object.
- Use secure, short-lived sessions or narrowly scoped tokens.
- Parameterize queries and encode output for its exact context.
- Protect keys and secrets through managed storage and rotation.
- Maintain dependency inventories, SBOMs and controlled build pipelines.
- Minimize personal data, define purpose and retention, and test deletion.
- Log security-relevant events without leaking sensitive information.
- Exercise incident response, recovery and communication plans.
- Reassess architecture when business purpose, dependencies or threats change.
Chapter SummaryIdentity, security and privacy engineering is a lifecycle discipline. Threat modelling identifies assets, trust boundaries and plausible attack paths; secure architecture applies least privilege, defense in depth and zero-trust principles. Authentication establishes identity, whereas authorization determines permitted actions and must be enforced for each sensitive resource. Sessions, cookies, bearer tokens, OAuth 2.0 and OIDC have distinct purposes and risks. Cryptography depends on sound key and nonce management, not merely strong algorithms. Secrets and dependencies require controlled supply-chain processes. Privacy requires minimization, purpose limitation, retention control and accountability, while incident response ensures that organizations can detect, contain, recover from and learn from failures. The most reliable programs combine technical controls, governance, testing, monitoring and ethical judgment. Key TermsAsset: A resource, capability or information value requiring protection. Authentication: Verification of a claimed identity. Authorization: Determination of permitted actions on resources. Bearer token: A token granting access to whoever possesses it. CSRF: An attack that causes a browser to send an unwanted authenticated request. CSP: A browser policy that restricts permitted content and script sources. Least privilege: Granting only the permissions required for an authorized task. Nonce: A value intended for one-time use in a cryptographic operation. OIDC: An identity layer built on OAuth 2.0. OAuth 2.0: A framework for delegated authorization. OWASP: An organization providing application-security guidance and resources. Pseudonymization: Replacing direct identifiers while retaining a controlled possibility of linkage. Risk: The potential for harm considered through likelihood and impact. STRIDE: A threat-modelling mnemonic covering six major threat categories. Supply-chain security: Protection of software dependencies, tools, builds and distribution. Threat model: A structured representation of assets, threats, trust boundaries and mitigations. Trust boundary: A separation between components with different security assumptions or authority. Zero trust: An approach that does not grant implicit trust based on network location. Review QuestionsShort Answer Questions1. Distinguish identification, authentication and authorization. 2. Why is server-side object-level authorization necessary even when identifiers are unpredictable? 3. State two security properties provided by authenticated encryption. 4. What is the principal difference between OAuth 2.0 and OpenID Connect? 5. Why is pseudonymization not equivalent to anonymization? Long Answer Questions1. Explain a complete threat-modelling process for a multi-tenant web application and discuss the role of trust boundaries. 2. Compare server-side sessions and JWT-based access tokens, including revocation, storage, scalability and leakage considerations. 3. Describe how zero-trust principles can be applied to a web application and its service-to-service APIs. 4. Explain how privacy by design influences data collection, retention, analytics and deletion. 5. Design an incident-response capability for a suspected credential-compromise event. Analytical / Application Questions1. A student can view another tenant's document by changing an object identifier in an API request. Identify the threat, explain the authorization defect and propose testing and architectural controls. 2. An organization wants to place long-lived JWTs in browser local storage to simplify a single-page application. Evaluate the proposal and recommend a safer design. 3. A dependency scanner reports a critical vulnerability in a package used only by an isolated administrative service. Develop a risk-based response covering validation, containment, remediation, supply-chain evidence and communication. Multiple Choice Questions with AnswersQuestion 1Which statement best distinguishes authentication from authorization? A. Authentication determines permitted actions, while authorization verifies identity. B. Authentication verifies identity, while authorization determines permitted actions. C. Authentication encrypts data, while authorization hashes passwords. D. Authentication records events, while authorization manages backups. Correct Answer: B. Authentication verifies identity, while authorization determines permitted actions. Question 2Which control most directly prevents an insecure direct object reference in a multi-tenant API? A. Making object identifiers longer B. Hiding identifiers from the user interface C. Checking the subject’s permission for the specific object and tenant D. Compressing the API response Correct Answer: C. Checking the subject’s permission for the specific object and tenant Question 3What is the primary purpose of PKCE in an OAuth authorization-code flow? A. To encrypt database records B. To bind the authorization request to the subsequent token exchange C. To replace TLS between the browser and server D. To provide password hashing Correct Answer: B. To bind the authorization request to the subsequent token exchange Question 4Which statement about OpenID Connect is correct? A. It is an identity layer built on OAuth 2.0. B. It is a database encryption standard. C. It eliminates the need for authorization checks. D. It requires all access tokens to be stored in local storage. Correct Answer: A. It is an identity layer built on OAuth 2.0. Question 5Which cookie attribute restricts a cookie to HTTPS transmission? A. HttpOnly B. SameSite C. Secure D. Domain Correct Answer: C. Secure Question 6What is the safest general method for storing user passwords? A. Reversible encryption with one shared key B. Plaintext with access restricted to administrators C. A slow password-hashing function with a unique salt per password D. Base64 encoding with a random prefix Correct Answer: C. A slow password-hashing function with a unique salt per password Question 7Which statement best expresses a zero-trust principle? A. Internal network traffic is automatically trusted. B. Trust is granted permanently after the first login. C. Network location alone is insufficient; requests are evaluated using identity and context. D. Only external users require authorization. Correct Answer: C. Network location alone is insufficient; requests are evaluated using identity and context. Question 8Why should a JWT consumer validate the audience claim? A. To ensure the token is intended for that receiving service B. To increase the token’s compression ratio C. To convert the token into an encrypted session D. To determine the user’s password strength Correct Answer: A. To ensure the token is intended for that receiving service Question 9Which practice is most consistent with privacy by design? A. Collect all potentially useful data indefinitely B. Collect the minimum data needed for a specified purpose and define retention C. Rely on encryption to remove all privacy obligations D. Share raw identifiers with every analytics provider Correct Answer: B. Collect the minimum data needed for a specified purpose and define retention Question 10Which activity is part of post-incident learning? A. Deleting all logs immediately after recovery B. Focusing only on which employee made the final mistake C. Examining failed assumptions and implementing systemic improvements D. Disabling monitoring to reduce alert volume Correct Answer: C. Examining failed assumptions and implementing systemic improvements
|