Web Security, Privacy, Accessibility, and EthicsIntroductionModern web applications are socio-technical systems. They process identity information, financial records, health data, communications, and behavioural information while serving users across devices and assistive technologies. Security therefore cannot be treated as a final testing activity. It must be designed into the application architecture, implementation, deployment process, and organisational culture. For React developers, this means understanding both browser security and server-side security. React can safely escape ordinary text rendered through JSX, but it does not eliminate risks involving unsafe HTML, authentication, APIs, dependencies, or server configuration. A secure interface must also be private by design, accessible to people with disabilities, inclusive of diverse users, and ethically responsible in its collection and use of data. Learning ObjectivesBy the end of this chapter, students should be able to: - Explain common web threats using the OWASP risk perspective.
- Prevent cross-site scripting, cross-site request forgery, injection, and authentication failures.
- Manage third-party dependencies and secrets responsibly.
- Apply privacy-by-design and data-minimisation principles.
- Build interfaces consistent with WCAG and inclusive-design practices.
- Evaluate consent, copyright, algorithmic decisions, and ethical data use.
- Analyse security and ethical trade-offs in a realistic React application.
1. A Security and Responsibility ModelA useful security model begins with the CIA triad: - Confidentiality means that information is available only to authorised parties.
- Integrity means that information and operations are not altered improperly.
- Availability means that legitimate users can access services when needed.
Web security also requires authenticity, accountability, and privacy. Authentication establishes who a user is; authorisation determines what that user may do. Accountability provides evidence about actions through carefully governed logging. Privacy concerns appropriate control over personal information, including collection, use, disclosure, retention, and deletion. The OWASP Top 10 is a widely used awareness framework. It highlights risks such as broken access control, cryptographic failures, injection, insecure design, security misconfiguration, vulnerable components, identification and authentication failures, software and data integrity failures, logging and monitoring failures, and server-side request forgery. It is not a complete security standard, but it is a valuable starting point for threat modelling and review. A professional workflow is: - Identify assets, actors, trust boundaries, and abuse cases.
- Estimate threats and potential impact.
- Select preventive and detective controls.
- Implement controls using secure defaults.
- Test, monitor, patch, and improve continuously.
Security is risk management rather than a claim that a system is absolutely secure. 2. Cross-Site ScriptingCross-site scripting (XSS) occurs when an attacker causes a victim’s browser to execute attacker-controlled script in the security context of a trusted website. XSS can steal information accessible to scripts, modify the page, perform actions as the victim, or deceive users. The main forms are: - Stored XSS: malicious content is saved by the application and later displayed to users.
- Reflected XSS: malicious input is immediately reflected in a response.
- DOM-based XSS: client-side code unsafely transfers data from a source such as the URL into a dangerous browser sink.
React escapes text interpolated in JSX. For example, rendering {comment} as text is safer than constructing HTML manually. However, dangerouslySetInnerHTML, unsafe URL handling, legacy libraries, direct DOM manipulation, and poorly designed server responses can reintroduce risk. Effective controls include: - Prefer text rendering over HTML rendering.
- Avoid
dangerouslySetInnerHTML; if it is essential, sanitise with a maintained, appropriately configured sanitizer. - Validate and constrain URL schemes, rejecting unexpected values such as
javascript:. - Encode output for its context rather than relying on input filtering alone.
- Use a restrictive Content Security Policy (CSP) as a defence-in-depth measure.
- Set cookies with
HttpOnly, Secure, and suitable SameSite attributes. - Keep dependencies and browser APIs updated.
Input validation and output encoding are different. Validation asks whether input meets the application’s permitted format. Encoding makes data safe for a particular output context. A string safe in HTML text may not be safe in a JavaScript string, CSS value, URL, or SQL query. 3. CSRF and Request IntegrityCross-site request forgery (CSRF) tricks an authenticated browser into sending an unwanted request to a trusted site. It is especially relevant when authentication depends on cookies, because browsers automatically attach matching cookies to requests. Common controls are: - Use
SameSite=Lax or SameSite=Strict cookies where compatible with the application. - Use a synchronised anti-CSRF token for state-changing requests.
- Check the
Origin or, where necessary, Referer header on the server. - Do not use GET for operations that change state.
- Require explicit reauthentication or step-up verification for highly sensitive actions.
A React client may attach a CSRF token to a request header, but the server must generate, validate, and bind the token appropriately. CORS is not a general CSRF defence. CORS controls which origins may read certain responses; it does not automatically prevent all cross-origin requests from being sent. 4. Injection and Trust BoundariesInjection occurs when untrusted data is interpreted as commands or code. SQL injection, NoSQL injection, operating-system command injection, template injection, and LDAP injection are examples. The central principle is to keep data separate from instructions. For database access, use parameterised queries or a carefully designed ORM. Never construct SQL by concatenating request parameters. For shell operations, avoid invoking a shell with user-controlled strings; use safe library APIs and fixed argument structures. Validate input using allowlists when the permitted domain is known, and apply least privilege to database and service accounts. Client-side validation improves usability but is not a security boundary. Every security-relevant rule must be enforced on the server. A React application should treat all API responses and user-supplied values as untrusted, even when they originated from its own interface. 5. Authentication, Authorisation, and SessionsAuthentication failures often arise from weak passwords, insecure recovery processes, credential stuffing, session theft, and incorrect authorisation checks. A secure design should: - Hash passwords with a modern adaptive password-hashing algorithm such as Argon2id, using an appropriate work factor.
- Permit long passphrases and avoid arbitrary complexity rules that encourage predictable substitutions.
- Rate-limit login and recovery attempts.
- Support multifactor authentication for sensitive accounts.
- Provide generic error messages that do not reveal whether an account exists.
- Rotate or invalidate sessions after login, privilege changes, and logout where appropriate.
- Enforce authorisation on every protected server-side operation.
A JSON Web Token (JWT) is not automatically safer than a server-side session. JWTs can be useful in some distributed architectures, but revocation, expiry, storage, key management, audience validation, and token leakage must be addressed. Storing long-lived tokens in localStorage increases exposure if XSS occurs. For many browser applications, a short-lived session identifier in a Secure, HttpOnly cookie, combined with CSRF protection, is a strong design. Authentication answers “Who are you?” Authorisation answers “What are you allowed to do?” A common vulnerability is trusting an object identifier supplied by a client without checking whether the authenticated user owns that object. This is an insecure direct object reference and a form of broken access control. 6. Dependencies, Secrets, and ConfigurationModern React applications rely on extensive package ecosystems. A vulnerable or malicious dependency can compromise an application even when the project’s own code appears correct. Good dependency governance includes: - Use lockfiles and reproducible builds.
- Review package maintainers, provenance, permissions, and update history.
- Remove unused packages.
- Run automated vulnerability scanning, while investigating rather than blindly accepting scanner output.
- Apply updates through review and testing.
- Protect the software supply chain with signed commits or builds where feasible.
- Generate a software bill of materials for important systems.
Secrets must never be committed to source control or embedded in client bundles. Environment variables exposed to frontend builds are not secret merely because they have a special name. Public configuration, such as an API base URL, may be shipped to the browser; private keys, database credentials, and signing secrets must remain server-side. Rotate exposed credentials promptly and restrict their permissions. Security headers, HTTPS, secure deployment settings, dependency controls, and error handling belong to configuration as well as code. Production systems should not expose stack traces, debug consoles, or administrative endpoints unnecessarily. 7. Privacy by DesignPrivacy is more than hiding a privacy policy. Privacy-by-design integrates protection into system architecture. Important principles include: - Data minimisation: collect only what is necessary for a specified purpose.
- Purpose limitation: do not reuse information for unrelated purposes without an appropriate basis and communication.
- Transparency: explain what is collected, why, for how long, and with whom it is shared.
- User control: provide practical access, correction, deletion, and preference mechanisms where applicable.
- Security: protect data throughout its lifecycle.
- Retention limitation: delete or anonymise information when it is no longer needed.
- Privacy by default: choose the least intrusive setting unless the user deliberately selects otherwise.
Consent must be informed, specific, freely given, and withdrawable where consent is the legal or ethical basis. A preselected checkbox or a confusing “accept” interface is not meaningful consent. Essential service operations should not be bundled with optional advertising consent. A data inventory should record categories of data, sources, purposes, systems, recipients, retention periods, access roles, and deletion mechanisms. Privacy impact assessments are useful when processing sensitive data, profiling people, monitoring behaviour, or introducing new technologies. Encryption in transit and at rest reduces exposure, but encryption does not solve excessive collection, inappropriate access, or unethical use. Logs should avoid unnecessary personal information and should have controlled access and retention. 8. Accessibility and Inclusive DesignAccessibility enables people with visual, auditory, motor, cognitive, and speech-related disabilities to perceive, operate, understand, and interact with a product. WCAG is organised around four principles: Perceivable, Operable, Understandable, and Robust. Its success criteria are commonly discussed at Levels A, AA, and AAA; many organisations target Level AA. Practical React practices include: - Use semantic HTML such as
button, nav, main, label, and heading elements. - Ensure every form control has an associated, meaningful label.
- Provide visible keyboard focus and a logical tab order.
- Do not make essential actions dependent on pointer hover or drag.
- Use sufficient colour contrast, but never communicate information by colour alone.
- Supply meaningful alternative text for informative images and empty alternative text for decorative images.
- Use captions and transcripts for multimedia.
- Manage focus when dialogs, routes, or asynchronous content change.
- Announce important status updates through appropriate accessible mechanisms.
- Test with keyboard navigation, zoom, screen readers, automated tools, and people with disabilities.
ARIA can improve custom controls, but it should not replace native semantic elements. A correctly implemented <button> is usually preferable to a div with a button role. Accessible design is not merely compliance: it improves usability for people using mobile devices, temporary injuries, slow networks, noisy environments, or unfamiliar interfaces. Inclusive design also considers language, culture, gender, age, literacy, connectivity, economic constraints, and neurodiversity. Avoid stereotypes, unnecessary personalisation, dark patterns, and assumptions about names, addresses, family structure, or ability. 9. Copyright, Licensing, and Ethical Data PracticeCode, images, fonts, videos, datasets, and documentation may be protected by copyright or other licences. Developers should record the source and licence of reused material, satisfy attribution requirements, comply with restrictions, and avoid assuming that publicly accessible content is free to copy. Open-source licences differ: some permit broad reuse, while others impose notice, attribution, source-disclosure, or distribution conditions. Ethical data practice asks not only whether processing is legal, but whether it is fair, proportionate, explainable, and beneficial. Important questions include: - Could the dataset exclude or disadvantage a group?
- Are people aware of secondary uses?
- Is the data accurate enough for the consequence imposed?
- Can a person challenge an automated decision?
- Are proxies being used for protected characteristics?
- Is the system collecting data because it is useful, or merely because it is available?
Artificial intelligence increases these concerns. Developers should document data provenance, evaluate model performance across relevant groups, protect confidential inputs, disclose meaningful automation, and maintain human review for high-impact decisions. An AI-generated answer or code sample must still be tested, licensed appropriately, and reviewed for security and bias. 10. Applied Case: CampusConnectBackgroundCampusConnect is an illustrative student-support portal built with React. It allows students to view appointments, upload documents, message advisers, and receive notifications. The first release stores a session token in browser storage, renders adviser messages as HTML, and collects date of birth for every account. ProblemA security review identifies several risks: stored XSS through messages, possible CSRF against cookie-based API operations, excessive personal-data collection, missing keyboard focus in a modal, and an endpoint that returns another student’s appointment when its identifier is changed. AnalysisThe message renderer crosses a trust boundary because adviser content may contain user-generated or imported text. The object-identifier problem is broken access control, not merely a frontend bug. The date of birth is not necessary for ordinary appointment booking, so its collection conflicts with data minimisation. The modal’s focus failure affects keyboard and screen-reader users. Finally, client-side route guards cannot protect the API if the server does not enforce permissions. Approach and SolutionThe team removes unnecessary date-of-birth collection and defines retention periods for documents and messages. It replaces raw HTML rendering with escaped text; where limited formatting is required, it applies a maintained allowlist sanitizer. The API uses server-side ownership checks and returns generic not-found responses where appropriate. State-changing requests use a CSRF token and secure cookie settings. Sessions are short-lived and invalidated on logout. The modal becomes a semantic dialog with labelled controls, trapped focus while open, and focus restoration on close. The team adds keyboard and screen-reader tests, dependency scanning, security headers, audit logging with minimised personal data, and an incident-response procedure. A privacy notice explains purposes, recipients, retention, and user choices in plain language. OutcomeThe revised system reduces attack surface, limits collected information, improves access for keyboard users, and gives the organisation evidence for security and privacy decisions. The team also changes its development process: threat modelling and accessibility review occur during design rather than after implementation. Learning PointsSecurity controls must be enforced at the server and supported by the client. Privacy and accessibility are architectural requirements, not cosmetic improvements. A single feature may create simultaneous security, legal, usability, and ethical consequences; effective professionals analyse all of them together. 11. Testing and Professional PracticeA mature assurance programme combines several techniques: - Static analysis: examines source code and configuration without executing the application.
- Dependency analysis: identifies known vulnerabilities and licence concerns.
- Dynamic testing: exercises the running system.
- Manual penetration testing: investigates realistic attack paths.
- Accessibility testing: combines automated checks with expert and user testing.
- Threat modelling: evaluates abuse cases before implementation.
- Code review: checks assumptions, trust boundaries, error handling, and maintainability.
No single tool proves security or accessibility. Automated tools commonly miss business-logic flaws, poor consent design, inaccessible interaction patterns, and vulnerabilities requiring context. Findings should be prioritised by likelihood, impact, exploitability, affected assets, and exposure. Developers should establish secure coding standards, protect production data, separate duties, document decisions, and provide a responsible vulnerability-reporting channel. Incident response should define preparation, detection, containment, eradication, recovery, communication, and post-incident learning. Challenges and LimitationsSecurity controls can introduce usability costs, false positives, performance overhead, and operational complexity. Strict session expiry may frustrate users; extensive consent interfaces may cause fatigue; aggressive sanitisation may remove legitimate formatting; and accessibility improvements may expose weaknesses in a poorly designed component library. These tensions should be managed through user research, risk assessment, progressive enhancement, and proportionate controls—not by abandoning protection. Legal requirements vary by jurisdiction and sector. Technical compliance does not guarantee ethical conduct, and a privacy notice cannot legitimise deceptive collection. Standards and browser behaviour also evolve, so professional competence requires continuous learning and maintenance. Chapter SummaryWeb security requires defence in depth across browser code, APIs, authentication, dependencies, configuration, and operations. React’s escaping is valuable but does not prevent unsafe HTML, access-control errors, insecure sessions, or vulnerable packages. XSS is reduced through safe rendering and context-aware output handling; CSRF through appropriate cookie policy, tokens, and server validation; injection through parameterisation and separation of data from commands; and authentication risk through strong password handling, multifactor authentication, secure sessions, and server-side authorisation. Privacy-by-design limits collection, clarifies purposes, protects information, and gives users meaningful control. WCAG’s principles guide accessible, perceivable, operable, understandable, and robust interfaces. Inclusive design extends beyond disability to language, culture, context, and unequal access. Copyright, licensing, consent, AI, and data ethics require professional judgement as well as technical knowledge. The central lesson is that trustworthy web development integrates security, privacy, accessibility, and ethics from requirements through retirement. Key TermsAccessibility: The ability of people with diverse abilities to use a product or service. Authentication: Verification of a user’s identity. Authorisation: Enforcement of what an authenticated subject is permitted to do. CORS: A browser mechanism controlling access to cross-origin responses. CSRF: An attack that causes a user’s browser to submit an unwanted authenticated request. CSP: A browser policy restricting permitted sources and behaviours for web content. Data minimisation: Collecting and retaining no more personal data than necessary. Dependency: External software package used by an application. Encryption: Transformation of information to protect confidentiality from unauthorised parties. Injection: Treating untrusted data as commands or executable instructions. Inclusive design: Designing for diverse abilities, identities, contexts, and circumstances. OWASP: An open community and body of guidance for application security. Privacy by design: Integrating privacy protections throughout system design and operation. Sanitisation: Removing or transforming unsafe content according to an allowlist and output context. Session: Server-recognised state representing an authenticated interaction. Stored XSS: XSS payload saved by an application and delivered to later users. WCAG: Web Content Accessibility Guidelines. Least privilege: Giving a subject only the access required for its task. Review QuestionsShort Answer Questions- Distinguish authentication from authorisation.
- Why does React’s normal JSX escaping not eliminate all XSS risks?
- State two controls that help prevent CSRF.
- What is meant by data minimisation?
- Name the four WCAG principles.
Long Answer Questions- Explain stored, reflected, and DOM-based XSS and compare their mitigations.
- Discuss how secure authentication, session management, and authorisation should be designed in a React application.
- Explain privacy-by-design principles and apply them to a student information portal.
- Describe an accessibility testing strategy that combines automated and human evaluation.
- Analyse the security and governance risks of third-party dependencies and secrets in frontend development.
Analytical / Application Questions- An application displays user comments with
dangerouslySetInnerHTML and stores long-lived tokens in localStorage. Identify the threats and propose a safer architecture. - A booking API accepts a student ID from the browser and returns appointment details without checking ownership. Classify the vulnerability and design server-side and client-side improvements.
- A company wants to collect precise location, contacts, and browsing history to personalise a service. Evaluate the proposal using privacy, consent, inclusion, security, and ethical-data principles.
Multiple Choice Questions with AnswersQuestion 1Which practice most directly prevents SQL injection? A. Using parameterised queries B. Adding more client-side form fields C. Hiding database errors in the browser D. Minifying the React bundle Correct Answer: A. Using parameterised queries Question 2What is the primary distinction between authentication and authorisation? A. Authentication encrypts data; authorisation compresses it B. Authentication verifies identity; authorisation determines permitted actions C. Authentication is client-side; authorisation is always optional D. Authentication prevents XSS; authorisation prevents CSRF Correct Answer: B. Authentication verifies identity; authorisation determines permitted actions Question 3Which React practice presents the greatest direct XSS risk? A. Rendering a string as ordinary JSX text B. Using semantic headings C. Using dangerouslySetInnerHTML with untrusted content D. Passing a value to a labelled input Correct Answer: C. Using dangerouslySetInnerHTML with untrusted content Question 4Why are CSRF tokens used? A. To make images load faster B. To prove that a state-changing request originated from an authorised application context C. To replace password hashing D. To provide colour contrast Correct Answer: B. To prove that a state-changing request originated from an authorised application context Question 5Which item is a privacy-by-design practice? A. Collecting every available attribute for possible future use B. Retaining personal data indefinitely C. Making optional tracking the default D. Collecting only data necessary for a specified purpose Correct Answer: D. Collecting only data necessary for a specified purpose Question 6Which element is normally preferable for a clickable action? A. A div with a click handler only B. A paragraph with a tabindex value C. A native button element D. An image with hidden text Correct Answer: C. A native button element Question 7What does the Secure cookie attribute help ensure? A. The cookie is sent only over HTTPS B. The cookie is readable by JavaScript C. The cookie never expires D. The cookie bypasses authorisation Correct Answer: A. The cookie is sent only over HTTPS Question 8Which is a form of broken access control? A. A user changes an object ID and receives another user’s private record B. A page uses a descriptive heading C. A package has a lockfile D. A form provides keyboard focus Correct Answer: A. A user changes an object ID and receives another user’s private record Question 9Which statement about CORS is correct? A. CORS automatically prevents every CSRF request B. CORS controls browser access to certain cross-origin responses C. CORS replaces server-side authorisation D. CORS hashes passwords Correct Answer: B. CORS controls browser access to certain cross-origin responses Question 10Which WCAG principle concerns keyboard operation and interaction? A. Perceivable B. Operable C. Understandable D. Robust Correct Answer: B. Operable
|