Web Application Development

Chapter 9
Identity, Security, Privacy, and Governance

Bachelors Program in Computer Science Engineering
Web Application Development   •   Bachelor

Identity, Security, Privacy, and Governance

Introduction

Web applications mediate valuable actions: users authenticate, organizations authorize access, browsers carry session state, and services exchange data across trust boundaries. A defect in any of these mechanisms can expose personal information, permit fraudulent transactions, or undermine an entire organization. Secure development is therefore not a final testing activity; it is a continuous discipline involving architecture, implementation, operations, governance, and accountability.

This chapter examines identity and access management, session security, tokens, OAuth 2.0 and OpenID Connect, common web vulnerabilities, cryptography and secrets, privacy, auditability, compliance, and incident response. The emphasis is on reasoning about threats and choosing controls proportionate to risk.

Learning Objectives

By the end of this chapter, a student should be able to:

  1. Distinguish authentication, authorization, accounting, identity, and access control.
  2. Design safer password, session, token, OAuth, and OpenID Connect flows.
  3. Explain and mitigate injection, cross-site scripting, cross-site request forgery, broken access control, and dependency risks.
  4. Select appropriate encryption, hashing, key-management, and secret-management practices.
  5. Apply privacy, consent, auditability, governance, and compliance principles.
  6. Construct a practical incident-response plan and evaluate security trade-offs.

1. Identity and Access as a Security Architecture

An identity is a representation of a person, service, device, or organization. Authentication answers “Who or what is this subject?” Authorization answers “What may this subject do to this resource under these conditions?” Accounting, sometimes called auditing, records what happened and supports accountability.

These functions should not be conflated. A valid login does not imply permission to read every customer record. Conversely, an authorization decision is meaningful only if the identity and session have been established reliably.

A useful access-control model contains:

  • Subject: the user, service, or device requesting an action.
  • Resource: an object such as an invoice, file, or API endpoint.
  • Action: read, create, update, delete, approve, or execute.
  • Context: tenant, time, device assurance, location, transaction value, and risk signals.
  • Policy: rules that determine whether the request is permitted.

The principle of least privilege gives each subject only the permissions required for legitimate work. Separation of duties prevents one identity from controlling mutually risky stages, such as creating and approving a payment. Fail-safe defaults deny access unless a policy explicitly permits it.

Authentication factors

Authentication commonly uses:

  • Knowledge: a password or PIN.
  • Possession: a hardware security key or authenticator device.
  • Inherence: a biometric characteristic.
  • Contextual evidence: device posture or location.

Multi-factor authentication combines independent factors. Two passwords are not two independent factors. Phishing-resistant methods, especially WebAuthn/FIDO2 security keys and platform authenticators, reduce exposure to credential theft because authentication is bound to the legitimate origin.

Passwords

Passwords should be accepted over encrypted connections and processed with a memory-hard, adaptive password-hashing algorithm such as Argon2id, or an appropriately configured alternative such as scrypt or bcrypt. Password hashing is not encryption: a hash is intended to be one-way, whereas encrypted data can be decrypted with a key.

A password database should store a unique salt and the password-hash parameters with each hash. A salt prevents identical passwords from producing identical stored values and makes precomputed rainbow tables ineffective. A server-side pepper may add protection, but it must be kept separately in a secret-management system. Passwords should not be logged, emailed, or stored in reversible form. Breached-password screening, rate limiting, carefully designed recovery, and MFA are more useful than arbitrary frequent expiry. Password managers and long passphrases should be supported.

2. Sessions, Cookies, and Tokens

HTTP is stateless, so applications create a session after authentication. A secure server-side session usually stores the authoritative state on the server and sends the browser only an unpredictable session identifier.

Session identifiers should be generated with a cryptographically secure random generator, transmitted only over HTTPS, regenerated after login or privilege elevation, and invalidated on logout, expiry, and suspected compromise. Applications should use short idle and absolute lifetimes appropriate to risk. High-value actions should require reauthentication or step-up authentication.

Important cookie attributes include:

AttributeSecurity purpose
SecureSends the cookie only over HTTPS.
HttpOnlyPrevents ordinary JavaScript from reading the cookie. It does not prevent all XSS effects.
SameSiteRestricts cross-site cookie sending and reduces CSRF risk.
Narrow Domain and PathLimits where the cookie is sent.
Appropriate expiryReduces the useful lifetime of stolen credentials.

A token is a credential representing claims, often used between services or APIs. A signed JSON Web Token (JWT) provides integrity and claims but is not confidential unless encrypted. JWTs require strict algorithm allow-lists, verification of signature, issuer, audience, expiry, and not-before claims, and protection against token substitution. A server must never trust claims merely because they are syntactically valid.

Access tokens should be short-lived and narrowly scoped. Refresh tokens require stronger protection, rotation, revocation strategy, and secure storage. Browser applications should avoid placing long-lived tokens in web storage when an HttpOnly, Secure cookie-based design can reduce JavaScript exposure. The correct choice depends on architecture and threat model; no storage mechanism eliminates XSS risk by itself.

3. OAuth 2.0 and OpenID Connect

OAuth 2.0 is an authorization framework for delegated access. It allows a client to obtain limited access to a resource server on behalf of a resource owner without receiving the owner’s password. OAuth is not, by itself, an authentication protocol.

OpenID Connect (OIDC) adds an identity layer to OAuth. An identity provider issues an ID token containing authenticated-user claims for a relying party. The relying party validates the token’s signature, issuer, audience, nonce, time claims, and relevant context.

For a browser-based application, the Authorization Code flow with Proof Key for Code Exchange (PKCE) is generally preferred. The client creates a high-entropy code_verifier, derives a code_challenge, and sends the challenge to the authorization server. Later it sends the verifier when redeeming the authorization code. The server accepts the code only if the verifier matches. This limits the value of an intercepted authorization code.

A sound flow includes:

  1. The client registers an exact redirect URI and uses HTTPS.
  2. The client generates and stores state to bind the response to the initiating request.
  3. The client generates a nonce for OIDC and later verifies it in the ID token.
  4. The authorization server authenticates the user and obtains consent where required.
  5. The client exchanges the short-lived code using PKCE.
  6. The client validates issuer, audience, signature, nonce, expiry, and code usage.
  7. The client requests minimal scopes and protects resulting tokens.

Redirect-URI matching, state validation, PKCE, consent integrity, and scope minimization are essential. Wildcard redirect URIs, open redirects, implicit token delivery in URLs, and accepting tokens from an untrusted issuer create serious risks.

4. OWASP Risks and Defensive Engineering

Security controls should be selected from a threat model rather than copied mechanically. The OWASP Top 10 is a useful awareness taxonomy, while detailed testing should use requirements, abuse cases, code review, dependency analysis, dynamic testing, and penetration testing.

Injection

Injection occurs when untrusted data changes the meaning of an interpreter command. SQL injection is prevented primarily through parameterized queries or safe query builders, not by string concatenation or superficial escaping. The database account should have only the permissions required by the application.

For example, an unsafe query conceptually combines input with syntax:

SELECT ... WHERE email = ' + userInput + '

A parameterized query instead sends SQL structure and values separately. Similar principles apply to command, LDAP, template, XPath, and expression injection. Validation should constrain type, length, range, and allowed format, but validation is not a substitute for contextual output encoding or parameterization.

Cross-site scripting

XSS occurs when attacker-controlled content executes as script in another user’s browser. Context-aware output encoding is the primary defense:

  • HTML text requires HTML encoding.
  • HTML attributes require attribute encoding and safe quoting.
  • JavaScript contexts require JavaScript-safe serialization.
  • URLs require URL parsing and scheme allow-lists.
  • CSS contexts require specialized controls.

Prefer frameworks with automatic escaping, avoid dangerous sinks such as raw HTML insertion, and use Content Security Policy as defense in depth. Sanitization is appropriate when trusted product functionality must accept limited markup, but it must use a mature, context-aware sanitizer. HttpOnly cookies reduce token theft but do not stop an attacker from performing actions through an XSS payload.

Cross-site request forgery

CSRF abuses a browser’s automatic inclusion of credentials to cause a state-changing request from another site. Defenses include SameSite cookies, unpredictable anti-CSRF tokens bound to the session, checking the Origin header where appropriate, and requiring reauthentication for sensitive actions. State-changing operations should not use GET. CSRF protections are still needed when cookies are used for authentication, even if the application has strong access control.

Broken access control

Every request must be authorized on the server, at the point where the resource and action are known. Never rely on hidden form fields, disabled buttons, client-side route guards, or predictable object identifiers. Object-level authorization checks that the current subject may access the specific record, not merely the endpoint, are essential. Test horizontal escalation (one user accessing another user’s data) and vertical escalation (a normal user invoking administrative functions).

Tenant identifiers should be derived from trusted server-side identity and policy context rather than accepted blindly from the client. Administrative operations should use separate roles, step-up authentication, approval workflows, and strong audit trails.

Insecure design, configuration, and dependencies

Threat modeling should occur before implementation and should identify assets, trust boundaries, abuse cases, and controls. Secure defaults include disabled debugging, restricted CORS, safe headers, minimal permissions, and explicit error handling that does not reveal secrets or internal topology.

Dependencies expand the attack surface. Organizations should maintain a software bill of materials where practical, pin and verify versions, monitor vulnerability advisories, remove unused packages, review transitive dependencies, and test updates in a controlled pipeline. A vulnerable package is not automatically exploitable, but ignoring exposure is poor risk management. Build systems and CI/CD credentials themselves require least privilege and strong authentication.

Other common risks include insecure deserialization, insufficient logging and monitoring, server-side request forgery (SSRF), and cryptographic failures. SSRF defenses include egress filtering, blocking internal and cloud metadata addresses, validating resolved addresses, and separating fetching services from privileged networks.

5. Cryptography, Transport, and Secrets

Confidentiality protects information from unauthorized disclosure; integrity detects unauthorized modification; authenticity links data or an action to a trusted source; non-repudiation is a stronger legal and technical claim that requires careful institutional assumptions.

Use current, well-reviewed cryptographic libraries rather than implementing algorithms. HTTPS should use properly configured TLS and valid certificates. Symmetric authenticated encryption, such as AES-GCM or ChaCha20-Poly1305, provides confidentiality and integrity when keys and nonces are managed correctly. A nonce must not be reused with the same key in schemes requiring nonce uniqueness. Passwords require password hashing, not general-purpose encryption.

Keys should have an owner, purpose, lifecycle, access policy, rotation and revocation process, backup or recovery plan, and destruction procedure. Key-management services or hardware security modules can isolate key operations. Rotation does not repair already compromised plaintext; incident response must assess exposure and replace affected credentials.

Secrets include API keys, database passwords, signing keys, certificates, and OAuth client secrets. They should be injected through a managed secret store, not committed to source control, embedded in client code, placed in images, or exposed in logs and crash reports. Secret scanning, short lifetimes, scoped permissions, and automated revocation reduce impact.

6. Privacy, Consent, and Data Governance

Security protects data against unauthorized access; privacy governs legitimate collection, use, sharing, retention, and individual rights. An application can be secure yet privacy-invasive if it collects excessive data or uses it for undisclosed purposes.

Privacy-by-design principles include:

  • Purpose limitation: collect and use data for specified legitimate purposes.
  • Data minimization: collect only what is necessary.
  • Accuracy: enable correction of materially inaccurate data.
  • Storage limitation: retain data only as long as justified.
  • Transparency: explain processing in understandable language.
  • User control: support applicable access, correction, deletion, portability, and objection rights.
  • Protection: apply appropriate technical and organizational safeguards.
  • Accountability: document decisions and demonstrate compliance.

Consent must be informed, specific, freely given, and withdrawable where consent is the legal basis. A preselected box, confusing interface, or “accept all” design that obscures alternatives undermines meaningful choice. Not every processing activity should rely on consent; applicable privacy law may recognize contractual necessity, legal obligation, or legitimate interests, subject to jurisdictional requirements.

A data inventory should identify categories, subjects, purposes, sources, recipients, locations, retention periods, legal basis, and risk. Data classification can distinguish public, internal, confidential, and highly restricted information. Privacy impact assessments are especially valuable for profiling, biometrics, large-scale monitoring, children’s data, and automated decision systems.

7. Auditability, Governance, and Compliance

An audit log records security-relevant events such as authentication outcomes, authorization failures, privilege changes, administrative actions, data exports, consent changes, and key lifecycle events. Logs should answer who acted, what occurred, which resource was affected, when it occurred, and from which relevant system context.

Logs must avoid passwords, access tokens, unnecessary personal data, and sensitive payloads. They require synchronized time, integrity protection, controlled access, retention rules, alerting, and a documented review process. Logging everything is not equivalent to accountability: excessive noise can conceal important events, while missing context prevents investigation.

Governance assigns responsibility. A security policy should define ownership, risk acceptance, exception handling, secure-development requirements, vulnerability disclosure, training, and review cadence. Compliance frameworks and laws differ by jurisdiction and industry; they should be mapped to actual processing and contractual obligations rather than treated as a checklist. Examples include privacy legislation, payment-card requirements, and security control frameworks. Legal counsel and qualified compliance professionals are needed for authoritative interpretation.

8. Incident Response and Resilience

No realistic system has zero risk. Incident response reduces harm through preparation, detection, containment, eradication, recovery, and lessons learned.

Preparation includes contact lists, asset inventories, backup testing, playbooks, forensic readiness, communication plans, and exercises. Detection and analysis establish whether an event is a false positive, vulnerability, or confirmed incident; preserve evidence and maintain a timeline. Containment limits spread, for example by disabling a compromised token, isolating a workload, or restricting egress. Eradication removes persistence and fixes the root cause. Recovery restores trusted operation while monitoring for recurrence. A post-incident review should improve controls without blaming individuals who acted reasonably within the system.

Notification duties may be time-sensitive and vary by jurisdiction, sector, contract, and type of data. The organization should coordinate security, privacy, legal, communications, leadership, and affected partners. Public statements must be accurate and avoid exposing additional victims.

9. Applied Case: Illustrative Multi-Tenant Learning Platform

Background

Consider LearnSpace, a fictional university platform that stores student profiles, grades, assignments, and payment records. It supports students, instructors, finance staff, and administrators across many institutions.

Problem

A security review finds that the browser stores a long-lived JWT in local storage, an API accepts a tenant identifier supplied by the client, an instructor endpoint checks only whether the caller is logged in, and a third-party package has a known vulnerability. The platform also logs full authorization headers and retains inactive student records indefinitely.

Analysis

The long-lived browser token increases the impact of XSS. The tenant identifier permits possible cross-tenant object access. Authentication without object-level authorization creates horizontal and vertical escalation. Logging authorization headers creates a secondary credential-exposure path. The vulnerable dependency and indefinite retention increase technical and privacy risk.

Approach and solution

The team first protects active risk: it revokes existing tokens, removes authorization headers from logs, patches or replaces the dependency, and reviews access logs for suspicious cross-tenant activity. It then designs a server-side session with Secure, HttpOnly, SameSite cookies, short idle expiry, rotation after login, and step-up authentication for grade export and payments.

Every API request derives the tenant from the authenticated identity and evaluates a policy against subject, resource, action, and tenant. Automated tests cover same-tenant success, cross-tenant denial, role escalation, and direct object references. The application uses parameterized queries, framework output encoding, CSRF protection, restrictive security headers, dependency scanning, and a managed secret store.

A data inventory defines retention periods for profiles, grades, payments, and audit records. Students receive a clear privacy notice, and data deletion or retention exceptions are handled through documented workflows. Security events are logged without tokens, forwarded to protected centralized storage, and monitored. An incident playbook and tabletop exercise are completed.

Outcome and learning points

The case illustrates that no single control is sufficient. Token storage, authorization, logging, dependency management, and retention are interconnected. A strong redesign combines prevention, detection, limitation of impact, privacy governance, and tested response. Most importantly, authorization is evaluated for each resource and action rather than inferred from successful login.

10. Contemporary Practice and Critical Issues

Modern applications increasingly use passwordless authentication, passkeys, zero-trust network principles, service-to-service identities, and policy-as-code. These approaches can improve assurance, but they introduce operational questions: how are authenticators recovered, how are service identities rotated, and who reviews policy changes?

Artificial intelligence creates additional security and privacy concerns. Models may expose memorized sensitive information, accept prompt injection, call tools with excessive authority, or generate insecure code. AI-assisted development requires human review, dependency and secret scanning, tests, provenance checks, and restrictions on sending confidential data to external services. An AI system should receive only the minimum permissions and context necessary for its task.

Security decisions are socio-technical. Strong controls that are unusable may encourage workarounds; privacy notices that no one understands do not produce meaningful transparency. Professionals must balance confidentiality, availability, usability, accessibility, cost, legal duties, and public trust. Risk acceptance should be explicit, documented, time-bounded, and owned by an accountable authority.

Best-Practice Checklist

  • Threat-model identity, data flows, trust boundaries, and abuse cases.
  • Use phishing-resistant MFA where feasible and secure password hashing where passwords remain.
  • Prefer short-lived, scoped credentials and rotate or revoke them appropriately.
  • Validate OAuth/OIDC issuer, audience, signature, nonce, state, redirect URI, and PKCE.
  • Enforce server-side, object-level authorization on every sensitive request.
  • Parameterize queries and apply context-aware output encoding.
  • Use CSRF defenses for cookie-authenticated state changes.
  • Patch, inventory, and monitor dependencies and build pipelines.
  • Encrypt data in transit and at rest, and manage keys and secrets separately.
  • Minimize personal data, define retention, obtain valid consent where required, and document purpose.
  • Log meaningful events without credentials or unnecessary sensitive data.
  • Exercise incident-response, backup, recovery, and notification procedures.

Chapter Summary

Identity security begins by separating authentication from authorization and accountability. Secure applications use strong authentication, carefully managed sessions, least privilege, object-level authorization, and phishing-resistant methods where possible. OAuth 2.0 delegates authorization, while OpenID Connect adds authentication; Authorization Code with PKCE, exact redirect URIs, state, nonce, and strict token validation are central safeguards.

Injection is controlled through parameterization, XSS through contextual encoding and safe rendering, CSRF through browser and request controls, and broken access control through server-side policy decisions for every resource and action. Cryptography requires appropriate algorithms, unique nonces where required, disciplined key management, and protected secrets. Privacy requires minimization, purpose limitation, transparency, retention control, and meaningful user rights. Auditability depends on useful, protected logs, while governance assigns responsibility and documents risk decisions. Finally, preparation, detection, containment, eradication, recovery, and learning form a practical incident-response lifecycle.

Key Terms

Authentication: Verification of the identity of a subject.

Authorization: Determination of which actions a subject may perform.

Least privilege: Granting only the permissions required for legitimate activity.

Multi-factor authentication: Authentication using independent factor categories.

Session: Server-recognized state representing an authenticated interaction.

Cookie: Browser-managed data often used to carry a session identifier.

Access token: Credential authorizing access to a protected resource.

Refresh token: Credential used to obtain new access tokens.

JWT: A structured token carrying claims, commonly integrity-protected by a digital signature.

OAuth 2.0: Framework for delegated authorization.

OpenID Connect: Identity layer built on OAuth 2.0.

PKCE: Proof Key for Code Exchange, which binds an authorization code to a client-generated verifier.

Injection: Manipulation of interpreter input so data changes command meaning.

XSS: Execution of attacker-controlled script in a victim’s browser context.

CSRF: Abuse of automatically sent browser credentials to cause an unwanted action.

Encryption: Reversible transformation providing confidentiality with a key.

Password hashing: One-way, deliberately expensive transformation used to store password verifiers.

Data minimization: Collecting and retaining no more personal data than necessary.

Audit log: Protected record of security-relevant activity.

Incident response: Coordinated process for handling and learning from security events.

Review Questions

Short Answer Questions

  1. Distinguish authentication from authorization and give one example of each.
  2. Why should a password be hashed rather than encrypted for database storage?
  3. What security properties do Secure, HttpOnly, and SameSite provide for cookies?
  4. Why is OAuth 2.0 not automatically an authentication protocol?
  5. State two principles of privacy by design.

Long Answer Questions

  1. Explain how a web application should manage sessions from login through logout, including rotation, expiry, cookie attributes, and reauthentication.
  2. Describe the Authorization Code flow with PKCE and explain the security role of state, nonce, redirect-URI validation, and token validation.
  3. Compare defenses against SQL injection, XSS, CSRF, and broken access control, emphasizing why each requires a different control.
  4. Explain how cryptographic keys and application secrets should be generated, stored, rotated, revoked, and audited.
  5. Describe the full incident-response lifecycle and discuss how privacy and legal requirements affect notification decisions.

Analytical / Application Questions

  1. A student can view another institution’s grade record by changing an identifier in an API request. Identify the control failure, propose a corrected authorization design, and specify three tests that should be added.
  2. An application stores a long-lived access token in browser local storage and allows user-generated HTML. Analyze the likely attack path and recommend layered mitigations.
  3. A company wants to collect precise location, biometric data, and browsing history “just in case.” Evaluate the proposal using purpose limitation, minimization, consent, retention, security, and governance principles.

Multiple Choice Questions with Answers

Question 1

Which statement best distinguishes authentication from authorization?

A. Authentication determines what a user may do; authorization verifies identity.

B. Authentication verifies identity; authorization determines permitted actions.

C. Authentication encrypts data; authorization hashes passwords.

D. Authentication records events; authorization deletes sessions.

Correct Answer: B. Authentication verifies identity; authorization determines permitted actions.

Question 2

Which control most directly prevents SQL injection?

A. Hiding database error messages only

B. Using parameterized queries

C. Adding a longer session timeout

D. Storing passwords in cookies

Correct Answer: B. Using parameterized queries

Question 3

What is the primary purpose of PKCE in an OAuth authorization-code flow?

A. To compress the access token

B. To bind the authorization code to a client-generated verifier

C. To replace TLS encryption

D. To provide database-level authorization

Correct Answer: B. To bind the authorization code to a client-generated verifier

Question 4

Which cookie attribute prevents ordinary client-side JavaScript from reading the cookie?

A. Secure

B. SameSite

C. HttpOnly

D. Domain

Correct Answer: C. HttpOnly

Question 5

Which practice is most appropriate for storing user passwords?

A. Reversible encryption with a database-held key

B. Plaintext with access restricted to administrators

C. A unique salt and an adaptive password-hashing algorithm

D. A fast unsalted hash

Correct Answer: C. A unique salt and an adaptive password-hashing algorithm

Question 6

A user changes an object ID in a request and sees another user’s record. What vulnerability is most directly demonstrated?

A. Broken object-level authorization

B. Weak TLS negotiation

C. Cross-site scripting

D. Insecure cookie formatting

Correct Answer: A. Broken object-level authorization

Question 7

Which statement about a signed JWT is correct?

A. It is automatically confidential.

B. It cannot expire.

C. Its signature can provide integrity, but confidentiality requires encryption.

D. Its claims never need issuer or audience validation.

Correct Answer: C. Its signature can provide integrity, but confidentiality requires encryption.

Question 8

Which privacy principle limits collection to data necessary for a stated purpose?

A. Data minimization

B. Non-repudiation

C. Privilege escalation

D. Token rotation

Correct Answer: A. Data minimization

Question 9

Which activity belongs primarily to incident containment?

A. Writing the initial privacy notice

B. Isolating a compromised workload and revoking exposed tokens

C. Designing a new application logo

D. Increasing data retention indefinitely

Correct Answer: B. Isolating a compromised workload and revoking exposed tokens

Question 10

Why should authorization headers generally be excluded from application logs?

A. They make timestamps inaccurate.

B. They can contain reusable credentials such as access tokens.

C. They prevent parameterized queries.

D. They disable browser caching.

Correct Answer: B. They can contain reusable credentials such as access tokens.

Web Application Development
Chapter 9 of 15