Web Technologies

Chapter 10
Web Security, Privacy and Digital Identity

Bachelors Program in AI & ML
Web Technologies   •   Bachelor

Web Security, Privacy and Digital Identity

Introduction and Context

Web applications process identity information, financial data, intellectual property, health records, and decisions produced by artificial-intelligence systems. Their exposure is unusually broad: a browser, mobile client, application programming interface (API), database, cloud service, administrator console, and third-party provider may all participate in one transaction. A weakness in any link can compromise confidentiality, integrity, availability, privacy, or accountability.

Web security is therefore more than adding encryption to a website. It is the disciplined protection of applications, users, identities, data, and supporting infrastructure against accidental and deliberate misuse. Privacy asks a related but distinct question: whether information is collected, used, disclosed, retained, and deleted in ways that are justified, transparent, and lawful. Digital identity concerns how a subject is represented, authenticated, authorized, and held accountable in an electronic system.

This chapter uses the principles of secure-by-design, least privilege, defense in depth, secure defaults, fail-safe behavior, and continuous verification. It emphasizes risks commonly represented in the OWASP Top 10, while recognizing that OWASP categories are educational risk groupings rather than a complete security standard.

Learning Objectives

After studying this chapter, a student should be able to:

1. Explain the security objectives of confidentiality, integrity, availability, authenticity, authorization, accountability, and privacy.

2. Identify and mitigate injection, cross-site scripting (XSS), cross-site request forgery (CSRF), and broken access control.

3. Explain TLS, secure cookies, sessions, OAuth 2.0, OpenID Connect (OIDC), and token security.

4. Design practical secrets-management and identity-verification controls.

5. Apply privacy-by-design and major regulatory principles without treating compliance as a substitute for security.

6. Analyze a web-security incident and propose preventive, detective, and corrective controls.

1. A Security Model for Web Systems

The traditional CIA triad consists of confidentiality, integrity, and availability. Confidentiality prevents unauthorized disclosure; integrity protects data and operations from unauthorized alteration; availability ensures that authorized users can obtain services when required. Web systems also require:

  • Authenticity: confidence that a user, service, message, or website is genuine.
  • Authorization: a decision about what an authenticated subject may do.
  • Accountability: the ability to associate actions with responsible identities through reliable logs and controls.
  • Non-repudiation: evidence that can make denial of a properly authenticated action difficult, although ordinary application logs do not automatically provide legal non-repudiation.
  • Privacy: appropriate control over information relating to identifiable or identifiable persons.

A useful distinction is authentication versus authorization. Authentication answers “Who are you?” Authorization answers “What may you do?” A valid login must never be treated as permission to access every object in the system.

Threat modeling makes security design explicit. A team identifies assets, trust boundaries, actors, entry points, threats, existing controls, and residual risk. STRIDE is one practical model: spoofing, tampering, repudiation, information disclosure, denial of service, and elevation of privilege. Risk assessment is not a precise prediction of loss; it is a structured aid to prioritization. A high-value database exposed through a public endpoint deserves stronger controls than a disposable development page.

2. Common Web Vulnerabilities and Their Defenses

2.1 Injection

Injection occurs when untrusted data is interpreted as commands or code. SQL injection is the familiar example. If an application constructs a query by concatenating input, an attacker may alter the query’s meaning. Similar problems occur in operating-system commands, LDAP queries, template engines, graph queries, and shell scripts.

The primary defense is parameterized querying, in which SQL code and values are transmitted separately:

```text

SELECT id, email FROM users WHERE email = ?

```

The database driver binds the supplied email as a value, not as SQL syntax. Object-relational mappers can help, but they do not make unsafe raw queries harmless. Input validation should enforce expected type, length, range, and format; it is a secondary control, not a replacement for parameterization. Allow-list validation is generally safer than trying to list every malicious string. Stored procedures are secure only when they themselves avoid dynamic, concatenated SQL. Database accounts should have the minimum required privileges.

Command injection requires avoiding shell invocation where possible, using an API that accepts structured arguments, validating commands against an allow-list, and running processes with restricted permissions. Output encoding is not a general injection defense because the correct encoding depends on the interpreter and context.

2.2 Cross-Site Scripting

XSS occurs when attacker-controlled content is executed as script in another user’s browser under the application’s origin. Reflected XSS is returned immediately in a response; stored XSS is persisted and later delivered to users; DOM-based XSS results from unsafe client-side processing.

The central defense is context-sensitive output encoding. HTML text, HTML attributes, JavaScript strings, CSS, and URLs have different grammars and therefore require different encoders. Framework auto-escaping should remain enabled. Applications should avoid inserting untrusted strings into `innerHTML`; safe text APIs such as `textContent` are preferable. A carefully designed Content Security Policy (CSP) can reduce impact, but CSP is defense in depth, not permission to retain unsafe injection.

Sanitizing HTML is more difficult than escaping plain text. If rich text is necessary, use a maintained, context-appropriate sanitizer and restrict permitted elements, attributes, and URL schemes. The `HttpOnly` cookie flag can prevent JavaScript from reading a cookie, but it does not prevent XSS from issuing requests as the victim or reading data visible in the page.

2.3 Cross-Site Request Forgery

CSRF exploits a browser’s tendency to attach ambient credentials, such as cookies, to a request initiated by another site. A malicious page might cause a victim’s browser to submit a transfer or change an email address.

Effective controls include unpredictable, session-bound anti-CSRF tokens checked on state-changing requests; the `SameSite` cookie attribute; verifying the `Origin` header where appropriate; and requiring reauthentication or step-up authentication for high-risk operations. State-changing actions should not use GET. CSRF tokens do not protect against XSS, because script executing in the trusted origin can usually read or submit the token. `SameSite=Strict` or `Lax` can reduce cross-site sending, but cookie behavior must be tested against legitimate cross-site login and integration flows.

2.4 Broken Access Control

Broken access control occurs when a user can perform an operation or access an object beyond the intended policy. An insecure direct object reference (IDOR) is a common instance: changing `/orders/1001` to `/orders/1002` reveals another customer’s order.

Authorization must be enforced server-side on every protected request. A robust object-level check evaluates both the requested object and the current principal, rather than trusting an identifier supplied by the client. Policies should be centralized and tested. Role-based access control assigns permissions to roles; attribute-based access control can additionally consider resource, ownership, time, location, or risk. Deny-by-default, least privilege, separation of duties, and explicit administrative authorization reduce exposure.

Changing an identifier to an opaque value is not authorization. Hiding a button is not authorization. Client-side route guards improve usability but cannot protect an API. Tests should include horizontal privilege escalation (one ordinary user accessing another’s data) and vertical escalation (an ordinary user invoking an administrator function).

2.5 Other Supporting Controls

Security also depends on secure configuration, dependency management, logging, error handling, and resilience. Error messages should help legitimate operators without exposing stack traces, credentials, or database structure. Logs should record security-relevant events, actor and target identifiers, timestamps, outcomes, and correlation IDs, while avoiding unnecessary sensitive data. Logs require access control, integrity protection, retention rules, and monitoring. Rate limiting, account lockout designed to resist denial-of-service abuse, multi-factor authentication, and anomaly detection address automated attacks.

3. TLS and Secure Communication

Transport Layer Security (TLS) provides encrypted and integrity-protected communication between endpoints and authenticates a server through a certificate chain. During a simplified TLS handshake, the client and server negotiate a protocol and cryptographic suite, the server proves possession of a private key associated with its certificate, and both derive session keys. Modern deployments should use current TLS versions and disable obsolete protocols and weak algorithms according to current platform guidance.

TLS protects data in transit between authenticated endpoints; it does not make a compromised server trustworthy, protect data after decryption, or guarantee that the user is interacting with the intended business logic. Certificate validation is essential. Applications should use HTTPS for the entire site, redirect HTTP carefully, enable HSTS after assessing deployment readiness, and prevent mixed content. APIs, internal services, and administrative interfaces also require authenticated and encrypted channels rather than assuming that an internal network is safe.

4. Cookies, Sessions, and Token Security

A session links multiple HTTP requests to a server-side or cryptographically protected state. A strong session identifier is generated by a cryptographically secure random generator, has sufficient entropy, is transmitted only over HTTPS, and is rotated after login or privilege change. Session expiration should include idle and absolute limits, with server-side invalidation for logout and high-risk events.

Important cookie attributes are:

  • Secure: send the cookie only over HTTPS.
  • HttpOnly: deny access through ordinary client-side JavaScript.
  • SameSite: restrict cross-site sending according to `Strict`, `Lax`, or `None` behavior. `None` requires Secure in modern browsers.
  • Domain and Path: limit where the cookie is sent; narrower scope is safer.

A cookie is a transport mechanism, not automatically a secure identity system. Do not place passwords or unnecessary personal data in cookies. Encrypting a value does not necessarily prevent replay; integrity, expiry, audience, rotation, and revocation must also be considered.

Bearer tokens grant access to whoever possesses them. They should be short-lived, transmitted only over protected channels, kept out of URLs, and not written to ordinary logs. Refresh tokens require stronger protection, rotation, reuse detection, and revocation. JWTs are signed claims containers, not inherently encrypted containers. A verifier must restrict accepted algorithms, validate signature, issuer, audience, subject, expiry, and not-before claims according to the application’s policy. It must not accept an algorithm merely because the token declares it. Sensitive data should generally not be placed in a JWT because decoding is easy even when signature verification is correct.

A stateful server session often offers simpler revocation and smaller client exposure. Stateless tokens can support distributed systems but introduce key rotation, revocation, audience, and stale-permission challenges. The design should follow the application’s actual requirements rather than treating JWTs as universally superior.

5. OAuth 2.0 and OpenID Connect

OAuth 2.0 is an authorization framework for delegated access. It allows a resource owner to authorize a client to obtain limited access to a resource server through an authorization server. OAuth does not, by itself, define user authentication. OIDC adds an identity layer and supplies an ID token describing an authentication event.

For browser-based applications, the Authorization Code flow with Proof Key for Code Exchange (PKCE) is the standard modern pattern. In outline:

1. The client creates a random code verifier and derives a challenge.

2. The browser is sent to the authorization server with client, redirect URI, scopes, state, and the challenge.

3. After authentication and consent, the authorization server returns a short-lived code to the registered redirect URI.

4. The client exchanges the code and verifier for tokens.

5. The resource server validates an access token intended for it.

The `state` value helps bind the response to the initiating transaction and mitigates login CSRF. OIDC additionally uses a nonce to bind an ID token to the authentication request. Redirect URIs must be exact and pre-registered; open redirects can undermine the flow. Access tokens should be audience-restricted and scopes should be narrow. An ID token is for the client, whereas an access token is for a resource server; confusing them is a serious design error.

Single sign-on improves usability but concentrates risk in the identity provider. Providers, clients, redirect endpoints, scopes, consent screens, recovery processes, and privileged accounts therefore require careful governance.

6. Secrets Management and Cryptographic Practice

Secrets include database passwords, API keys, private keys, signing keys, webhook secrets, and service credentials. They should not be committed to source control, embedded in frontend bundles, placed in container images, or copied into tickets and chat. A secret manager should provide encrypted storage, controlled retrieval, identity-based access, audit trails, rotation, versioning, and emergency revocation. Applications should receive only the secrets they need, preferably at runtime.

Key management distinguishes encryption at rest from access control. Encryption does not help if every compromised application account can decrypt everything. Separate environments, restrict administrative access, rotate keys according to risk, and plan recovery before an incident. Passwords must be salted and processed with a dedicated password-hashing scheme such as Argon2id, scrypt, or bcrypt using parameters appropriate to current hardware. Password encryption that can be reversed is not an acceptable substitute for password hashing.

Use established, reviewed cryptographic libraries. Randomness for tokens, reset links, and keys must be generated by a cryptographically secure random source. Do not design proprietary algorithms or compare secrets with ordinary early-exit string comparisons when timing exposure matters; use suitable constant-time library functions where applicable.

7. Privacy by Design and Regulation

Privacy-by-design integrates privacy into architecture rather than adding a policy after implementation. Its practical principles include:

  • Purpose limitation: collect and use data for specified legitimate purposes.
  • Data minimization: collect only what is necessary.
  • Storage limitation: retain data only as long as justified.
  • Accuracy: provide correction mechanisms.
  • Transparency: explain processing in understandable language.
  • User control: support applicable access, correction, deletion, portability, and objection rights.
  • Security: protect confidentiality, integrity, and availability.
  • Accountability: document decisions, responsibilities, and evidence.

Regulatory obligations vary by jurisdiction and sector. Frameworks such as the EU General Data Protection Regulation (GDPR), state privacy laws, consumer-protection law, breach-notification requirements, and health or payment regulations may apply differently according to location, role, data type, and processing purpose. A privacy notice is not consent by itself, and consent is not always the correct legal basis. Organizations should involve legal and privacy specialists in determining lawful basis, processor/controller roles, cross-border transfer requirements, retention, and incident notification.

Pseudonymization reduces direct identifiers but does not necessarily make data anonymous; linkage attacks can re-identify records. Anonymization is a stronger claim requiring analysis of reasonably available auxiliary information. Privacy impact assessments are valuable before launching high-risk profiling, biometric processing, large-scale monitoring, or AI systems.

AI introduces special concerns. Training data may contain personal information, model outputs may memorize or infer sensitive attributes, and prompts may leak confidential records. Controls include dataset minimization, access restrictions, retention limits, redaction, evaluation for memorization and inference, human oversight, provenance records, and clear user notices. Security and privacy risks in an AI-enabled web service should be assessed as a system, including models, plugins, retrieval stores, logs, and operational personnel.

8. Secure Development and Assurance

Security is a lifecycle activity. Requirements should identify assets, abuse cases, privacy obligations, and unacceptable outcomes. Design reviews should examine trust boundaries, identity flows, authorization decisions, data stores, and failure modes. Implementation should use secure frameworks and peer review. Testing should include unit tests for policies, integration tests for authentication and authorization, dependency scanning, static and dynamic analysis, fuzzing, configuration review, and targeted penetration testing. Automated tools find patterns but do not understand every business authorization rule.

A mature program includes vulnerability disclosure, patch prioritization, incident response, backups, disaster recovery, supplier assessment, and post-incident learning. Security controls should be measurable through indicators such as time to remediate critical vulnerabilities, percentage of privileged accounts protected by multi-factor authentication, secret exposure events, authorization-test coverage, and successful recovery exercises. Metrics must be interpreted carefully: a low count of detected incidents may mean poor detection rather than low risk.

9. Illustrative Case Study: University Research Portal

Background

A university operates a portal through which students upload research data and supervisors review submissions. The portal uses a single-page web client, an API, object storage, an identity provider, and an AI service that summarizes documents.

Problem

A security review discovers that changing a submission ID in an API request reveals another student’s document. The application stores a long-lived access token in browser local storage. A rich-text comment field renders HTML without reliable sanitization. The AI service receives entire documents, including student identifiers, and the privacy notice does not clearly describe this processing.

Analysis

The submission flaw is broken object-level authorization. The token storage increases the impact of XSS because injected JavaScript can read the token. Unsanitized comments create stored XSS, which could then perform authenticated actions. Sending unnecessary identifiers to the AI provider violates minimization and creates supplier, retention, and disclosure questions. These are connected risks rather than isolated defects.

Approach and Solution

The university first restricts the affected endpoints and preserves relevant logs without exposing documents further. The API introduces a centralized policy that verifies the authenticated user’s relationship to each submission and separately checks supervisor privileges. Authorization tests cover horizontal and vertical escalation.

The application replaces unsafe HTML rendering with plain text where rich formatting is not essential; where it is essential, it uses a maintained allow-list sanitizer and output encoding. A CSP is deployed in reporting mode before enforcement. Tokens are redesigned using a short-lived access token and protected session strategy, with secure, HttpOnly, appropriately scoped cookies where compatible with the architecture. CSRF protections are added to state-changing cookie-authenticated requests.

The AI workflow removes direct identifiers, documents the purpose and retention period, restricts provider access, and offers a non-AI alternative where required. The university updates its privacy assessment and notice, establishes deletion procedures, rotates exposed credentials, and monitors suspicious access.

Outcome

The portal no longer relies on client-side hiding for authorization, stored comments cannot execute arbitrary script under normal input, and the AI service receives minimized data. The university also gains repeatable security tests and an incident-response process.

Learning Points

Security failures compound. A single XSS defect becomes substantially more damaging when tokens are readable; weak authorization converts a session compromise into broad data exposure; and technically successful AI processing may still be impermissible if purpose, minimization, and transparency are absent.

10. Challenges, Trade-offs, and Best Practices

Security controls create operational and usability costs. Strict session expiry can frustrate users; extensive logging can create privacy risk; multi-factor authentication requires recovery design; encryption can complicate searching and analytics; and aggressive rate limits can block legitimate traffic. Good engineering makes these trade-offs explicit and tests them with representative users.

A practical baseline is to inventory data and identities; enforce HTTPS; use parameterized queries and context-aware output encoding; centralize authorization; protect sessions and cookies; adopt phishing-resistant multi-factor authentication for sensitive roles; use PKCE for public OAuth clients; validate tokens for issuer, audience, time, and signature; manage secrets centrally; minimize and classify personal data; maintain secure dependencies; log meaningful security events; test recovery; and rehearse incident response. Controls should be reviewed whenever architecture, suppliers, regulations, or threat conditions change.

Chapter Summary

Web security protects confidentiality, integrity, availability, authenticity, authorization, accountability, and privacy. Injection is mitigated primarily through parameterized interfaces and least-privileged accounts. XSS requires context-sensitive output encoding, safe DOM practices, and carefully deployed defense in depth. CSRF controls include tokens, suitable cookie policies, origin checks, and safe HTTP semantics. Broken access control must be enforced server-side for every object and operation.

TLS protects communication in transit but does not secure compromised endpoints. Secure sessions require strong identifiers, rotation, expiry, invalidation, and correctly scoped cookies. OAuth 2.0 delegates authorization, while OIDC adds authentication; PKCE, state, nonce, exact redirect URIs, narrow scopes, and correct token audiences are essential. Secrets require centralized management, restricted access, rotation, and auditing. Privacy-by-design applies purpose limitation, minimization, transparency, retention control, user rights, and accountability. Secure development combines threat modeling, testing, monitoring, incident response, and continuous improvement. In AI-enabled systems, models and data pipelines must be included in the same security and privacy analysis.

Key Terms

Confidentiality: Protection against unauthorized disclosure of information.

Integrity: Protection against unauthorized alteration or destruction.

Authentication: Verification of a subject’s claimed identity.

Authorization: Determination of what an authenticated subject may do.

Injection: Treating untrusted data as commands or executable syntax.

Cross-site scripting (XSS): Execution of attacker-controlled script in a trusted web origin.

Cross-site request forgery (CSRF): Abuse of automatically attached credentials to induce an unwanted request.

Broken access control: Failure to enforce intended permissions on operations or objects.

TLS: Protocol providing authenticated, encrypted, and integrity-protected communication.

Session: State linking related requests to an authenticated interaction.

Cookie: Browser-managed data sent with requests according to defined attributes.

OAuth 2.0: Framework for delegated authorization.

OpenID Connect: Identity layer built on OAuth 2.0.

PKCE: Mechanism binding an authorization-code exchange to the initiating client.

Bearer token: Token granting access to whoever possesses it.

JWT: Compact signed and/or encrypted claims representation.

Secrets manager: Controlled service for storing, retrieving, rotating, and auditing secrets.

Data minimization: Limiting collection and processing to what is necessary.

Pseudonymization: Replacing identifying attributes while retaining a possibility of linkage.

Content Security Policy: Browser policy restricting permitted content and script behaviors.

Review Questions

Short Answer Questions

1. Distinguish authentication from authorization and give one example of each.

2. Why is parameterized SQL safer than concatenating user input into a query?

3. State the purpose of the Secure, HttpOnly, and SameSite cookie attributes.

4. What additional capability does OpenID Connect provide beyond OAuth 2.0?

5. Explain why pseudonymized data may still be personal data.

Long Answer Questions

1. Explain injection, XSS, CSRF, and broken access control, comparing their attack mechanisms and principal defenses.

2. Describe a secure browser-based OAuth 2.0 Authorization Code flow with PKCE, including the roles of state, nonce, redirect URIs, access tokens, and ID tokens.

3. Discuss the security advantages and limitations of stateful sessions and stateless JWT-based authentication.

4. Explain how privacy-by-design principles should influence the architecture of an AI-enabled web application.

5. Design a secure secrets-management lifecycle for a university web service, from creation through rotation and revocation.

Analytical / Application Questions

1. An API allows a logged-in student to request any document by changing an ID in the URL. Analyze the vulnerability and propose server-side controls and tests.

2. A web application stores long-lived refresh tokens in local storage and contains a stored XSS flaw. Evaluate the likely impact and recommend a staged remediation plan.

3. A research portal sends complete identifiable documents to an external AI summarization service. Develop a security and privacy assessment covering data minimization, authorization, retention, suppliers, user transparency, and incident response.

Multiple Choice Questions with Answers

Question 1

Which control is the primary defense against SQL injection?

A. Hiding database error messages

B. Parameterized queries

C. Using longer URLs

D. Adding a CAPTCHA to every request

Correct Answer: B. Parameterized queries

Question 2

What is the main purpose of the HttpOnly cookie attribute?

A. To prevent the cookie from being sent over HTTP

B. To prevent cross-site requests in all cases

C. To prevent ordinary JavaScript from reading the cookie

D. To encrypt the cookie contents

Correct Answer: C. To prevent ordinary JavaScript from reading the cookie

Question 3

Which statement correctly distinguishes OAuth 2.0 from OpenID Connect?

A. OAuth provides encryption, while OIDC provides hashing

B. OAuth delegates authorization, while OIDC adds an identity layer

C. OAuth is only for databases, while OIDC is only for browsers

D. OAuth replaces TLS, while OIDC replaces cookies

Correct Answer: B. OAuth delegates authorization, while OIDC adds an identity layer

Question 4

Why is changing an object ID to access another user’s record a security problem?

A. It is a compression failure

B. It is broken object-level access control

C. It is certificate expiration

D. It is a DNS poisoning attack

Correct Answer: B. It is broken object-level access control

Question 5

Which measure most directly mitigates CSRF for a state-changing cookie-authenticated request?

A. A server-validated anti-CSRF token

B. A larger database index

C. A public access token in the URL

D. Disabling output encoding

Correct Answer: A. A server-validated anti-CSRF token

Question 6

What does TLS primarily provide between correctly authenticated endpoints?

A. Authorization for every database row

B. Encrypted and integrity-protected communication

C. Automatic removal of malware from servers

D. Permanent identity verification of every user

Correct Answer: B. Encrypted and integrity-protected communication

Question 7

Why should an access token not automatically be accepted as an OIDC ID token?

A. They always use different network protocols

B. They have different intended audiences and purposes

C. ID tokens cannot contain claims

D. Access tokens are always encrypted and ID tokens are never signed

Correct Answer: B. They have different intended audiences and purposes

Question 8

Which practice is most appropriate for storing user passwords?

A. Reversible encryption with one global key

B. Plaintext storage with restricted database access

C. A dedicated password-hashing scheme with a unique salt

D. A Base64-encoded database column

Correct Answer: C. A dedicated password-hashing scheme with a unique salt

Question 9

Which privacy principle limits collection to information necessary for a specified purpose?

A. Data minimization

B. Non-repudiation

C. Fail-open design

D. Algorithm substitution

Correct Answer: A. Data minimization

Question 10

What is a key limitation of CSP as an XSS defense?

A. It cannot be delivered to browsers

B. It is defense in depth and does not replace safe handling of untrusted data

C. It only protects database passwords

D. It disables TLS certificate validation

Correct Answer: B. It is defense in depth and does not replace safe handling of untrusted data

Web Technologies
Chapter 10 of 14