Cross-Site Scripting (XSS) in Java and React: Security Architect's Perspective (Part 3)

In Part 1, we examined reflected and stored XSS from a developer's perspective, covering how malicious input travels from server to browser and secure coding patterns using DOMPurify and OWASP Java HTML Sanitizer. Part 2 extended those concepts to DOM-based XSS, framework pitfalls, postMessage vulnerabilities, Content Security Policy, and automated detection pipelines.
This part shifts focus from code to strategy. Security architects must translate vulnerability knowledge into organizational controls, risk frameworks, and measurable security programs. Knowing how to fix XSS is necessary but insufficient. The real challenge is building systems and processes that prevent these vulnerabilities from reaching production in the first place.
The metrics, security gates, remediation SLAs, training structure, and incident response lifecycle are the same for every vulnerability class, and Building an Application Security Metrics Program: Measuring What Actually Matters already covers them. We point to that post wherever the shared machinery applies and spend this one on what XSS changes: the threat model, the scoring of a finding, the architecture controls, the compliance mappings, and the XSS-specific checks at each stage.
The OWASP Top 10:2025 places XSS (CWE-79) under A05:2025 Injection, a category that fell from third place in 2021 to fifth. The lower rank does not make XSS rare. OWASP counts more than 30,000 XSS CVEs in the dataset behind this edition and describes the class as high frequency and low impact. A flaw that keeps appearing at that rate after decades of awareness is a security program problem: it takes architecture, governance, and continuous measurement to keep it out of production.
1. Threat modeling XSS
Before implementing controls, security architects must understand the threat landscape. XSS is not a monolithic risk. Different attack scenarios carry different business impacts and require different mitigation strategies.
Attack scenarios and business impact
Session Hijacking
The classic XSS objective is stealing session tokens. Attackers capture cookies or tokens accessible to JavaScript and replay them to impersonate victims. Business impact includes unauthorized access to user accounts, potential compliance violations, and reputational damage if the attack scales. A single successful hijacking can lead to complete account takeover.
Credential Theft
Attackers inject fake login forms or keyloggers that capture credentials as users type. The payload can exfiltrate data to attacker-controlled servers in real time. Business impact extends beyond the compromised application since users often reuse passwords across services.
Malware Distribution
XSS can redirect users to malicious sites or trigger drive-by downloads. The trusted domain serves as a launchpad for broader attacks. Business impact includes legal liability and loss of customer trust when a trusted domain is used to attack its own users.
Defacement and Phishing
Attackers modify page content to display misleading information, phishing forms, or propaganda. Business impact includes brand damage, user confusion, and potential regulatory scrutiny if financial or health information is misrepresented.
Worm Propagation
Self-propagating XSS worms spread automatically by posting malicious content as each victim. The Samy worm on MySpace demonstrated this in 2005, affecting over a million users in under 20 hours. Business impact includes service disruption, data integrity issues, and emergency response costs.
Mapping to STRIDE
Security architects often use the STRIDE model to categorize threats. XSS maps across multiple categories:
| STRIDE Category | XSS Manifestation |
|---|---|
| Spoofing | Injecting fake login forms, impersonating legitimate UI elements |
| Tampering | Modifying displayed content, altering form values before submission |
| Repudiation | Performing actions that appear to come from the victim |
| Information Disclosure | Stealing cookies, tokens, keystrokes, and page content |
| Denial of Service | Infinite loops, resource exhaustion, or breaking page functionality |
| Elevation of Privilege | Performing admin actions in the context of a privileged user (Blind XSS) |
This multi-category impact explains why XSS consistently appears in vulnerability taxonomies. It is not a single threat but a gateway to many.
Attack tree analysis
A simplified attack tree for XSS helps identify control points:
Each node represents an opportunity for controls. Defense in depth means placing obstacles at multiple points, so failure at one level does not mean complete compromise.
2. Risk-based prioritization
Not all XSS findings require immediate remediation. Security architects must prioritize based on risk, balancing security investment against business constraints.
CVSS contextualization
The Common Vulnerability Scoring System provides a baseline, but raw CVSS scores lack business context. An XSS vulnerability in an internal reporting tool differs dramatically from one in a customer-facing payment portal.
CVSS v4.0 is the current version. It drops the v3.1 Scope metric and scores impact on the vulnerable system separately from impact on subsequent systems. For XSS, the vulnerable system is the web application that fails to neutralize the input, and the subsequent system is the victim's browser, where the injected script runs.
Base Metric Values for XSS:
| Metric | Typical Value | Reasoning |
|---|---|---|
| Attack Vector (AV) | Network | The payload is delivered over HTTP |
| Attack Complexity (AC) | Low | No security mechanism has to be evaded where output encoding is missing |
| Attack Requirements (AT) | None | No race condition or on-path position is needed |
| Privileges Required (PR) | None/Low | None for most reflected XSS; Low when the attacker needs an account to store the payload |
| User Interaction (UI) | Active/Passive | Active when the victim must open a crafted link; Passive when a stored payload fires during normal browsing |
| Vulnerable System Confidentiality and Integrity (VC/VI) | None to High | Depends on what the script can read and change in the application through the victim's session |
| Vulnerable System Availability (VA) | None | Typically no effect on the application's availability |
| Subsequent System Confidentiality and Integrity (SC/SI) | Low | The script reads and modifies data in the victim's browser |
| Subsequent System Availability (SA) | None | No direct availability impact on the browser |
FIRST's scored examples rate a reflected XSS (CVSS:4.0/AV:N/AC:L/AT:N/PR:N/UI:A/VC:N/VI:N/VA:N/SC:L/SI:L/SA:N) at 5.1. A stored XSS that needs an account and fires on a normal page view (PR:L/UI:P with the same impact values) also scores 5.1. The score climbs with what the victim's session can do in the application: FIRST's example of an XSS whose script can trigger command execution with the victim's privileges (PR:L/UI:A/VC:H/VI:H/VA:H/SC:L/SI:L/SA:N) scores 8.5, and FIRST notes that this case may be atypical of XSS.
Many scanners and advisories still publish CVSS 3.1 scores. There, the usual reflected XSS vector (AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:L/A:N) scores 6.1, or 5.4 when the attacker needs an account (PR:L). The same unauthenticated vector with high confidentiality and integrity impact (C:H/I:H) scores 9.3. The two versions calculate differently, so record the version and vector with every score. Threat and environmental factors still matter enormously.
Environmental Adjustments:
- Is the vulnerable application internet-facing or internal only?
- What data classification applies to accessible information?
- Are there compensating controls (CSP,
HttpOnlycookies)? - What is the user population (admins vs. general public)?
CVSS v4.0 records these adjustments in its Threat and Environmental metric groups and labels the result CVSS-BT, CVSS-BE, or CVSS-BTE.
Risk scoring framework
A practical risk scoring approach for XSS findings:
| Factor | Weight | Scoring Criteria |
|---|---|---|
| Data Sensitivity | 30% | PII/PHI/PCI = High, Internal = Medium, Public = Low |
| Exposure | 25% | Internet-facing = High, Partner = Medium, Internal = Low |
| XSS Type | 20% | Stored = High, DOM-based = Medium, Reflected = Medium-Low |
| User Population | 15% | Admins = High, All users = Medium, Limited = Low |
| Compensating Controls | 10% | None = High risk, Partial (CSP) = Medium, Strong = Low |
This framework enables consistent prioritization across a vulnerability backlog and helps justify remediation timelines to stakeholders.
Remediation SLAs
Feed the resulting risk level into the remediation SLA tiers, escalation path, and exception process defined in the application security metrics program. XSS does not need its own timelines. That post's examples put stored XSS in a customer-facing portal in the high tier and reflected XSS that needs social engineering in the medium tier. The factors above move a finding away from those defaults: stored XSS that reaches every user of an application with no CSP belongs in the critical tier, while reflected XSS in an internal tool behind a strong CSP can drop to low.
3. Security architecture controls
Beyond secure coding, architects design systemic controls that reduce XSS risk across the organization.
Architectural patterns
Separation of Data and Presentation
The fundamental architectural defense against XSS is separating data from presentation. Backend services should return structured data (JSON), not HTML fragments. Frontend frameworks handle rendering with built-in escaping.
This pattern removes server-side HTML building as a source of XSS, because user data never becomes HTML on the server. DOM-based XSS still depends on how the client renders that data, which is the subject of Part 2.
Centralized Sanitization Service
When HTML content is genuinely required, centralize sanitization in a dedicated service. This creates a single point for security controls, auditing, and updates.
This pattern ensures consistent sanitization regardless of which API accepts the content. It complements the client-side sanitization wrapper from Part 2 and does not replace sanitizing at the point of rendering.
Content Security Policy as Infrastructure
CSP should be managed as infrastructure, not per-application configuration. Define the policy centrally and deliver it through a shared component, so every application starts from the same baseline and updates roll out in one place. An API gateway or reverse proxy can emit a static policy. A nonce-based policy needs more than that: the nonce in the header has to match the nonce on every script tag in the same response, so the component that renders the HTML must take part, as the nonce filter in Part 2 does.
Defense layers
Layer 1: Input Validation
Validate input at the API boundary. Reject malformed requests early. This is not sufficient for XSS prevention but reduces attack surface.
Layer 2: Output Encoding
Context-aware output encoding is the primary defense. Use framework defaults (React JSX, Thymeleaf th:text) and opt out only through a reviewed entry point that sanitizes the content. Auto-escaping does not validate URLs, so check the scheme of user-supplied links separately.
Layer 3: Sanitization
For rich content, sanitize using established libraries (DOMPurify, OWASP Java HTML Sanitizer). Never build custom sanitizers.
Layer 4: Content Security Policy
CSP provides defense in depth. Even if XSS occurs, CSP can prevent payload execution by blocking inline scripts.
Layer 5: Cookie Hardening
HttpOnly cookies prevent JavaScript access to session tokens. SameSite limits cross-site cookie sending, which helps against CSRF. Neither stops injected script from sending same-origin requests with the victim's cookies attached.
Layer 6: Monitoring and Detection
WAF rules, CSP violation reports, and anomaly detection provide visibility into attempted attacks. The reports exist only if the policy names a reporting endpoint: report-to together with the Reporting-Endpoints header, plus report-uri for browsers that do not support report-to yet. A DOM-based payload carried in the URL fragment never reaches the server, so the WAF cannot see it.
4. Compliance and regulatory mapping
XSS vulnerabilities have direct compliance implications. Security architects must understand these mappings to communicate risk in business terms.
PCI DSS requirements
For organizations handling payment card data, PCI DSS v4.0.1 is the current version of the standard:
| Requirement | XSS Relevance |
|---|---|
| 6.2.1 | Develop bespoke and custom software securely, based on industry standards |
| 6.2.4 | Engineering techniques prevent or mitigate common attacks, including XSS |
| 6.3.1 | Identify and risk-rank security vulnerabilities |
| 6.4.2 | Protect public-facing web applications with an automated solution that continually detects and prevents web-based attacks |
| 6.4.3 and 11.6.1 | Authorize, inventory, and integrity-check payment page scripts, and detect unauthorized changes to payment pages as the consumer's browser receives them |
| 11.4.1 | Penetration testing methodology includes application-layer testing for the vulnerabilities listed in 6.2.4 |
Requirement 6.2.4 names XSS among the attacks that secure development must prevent or mitigate. Older documents cite Requirement 6.5.7 from v3.2.1, which was retired in March 2024. Requirements 6.4.3 and 11.6.1, both mandatory since 31 March 2025, matter just as much here, because injected script on a payment page is exactly how client-side card skimming works. A confirmed XSS vulnerability in a cardholder data environment puts PCI compliance at risk. The consequences of non-compliance, such as fines or the loss of card processing, are set by the payment brands and acquirers, not by the standard itself.
GDPR implications
Where the processing falls within GDPR's scope, XSS exposing personal data requires an assessment of:
- Article 32: Whether the technical and organisational measures were appropriate to the risk; a breach alone does not establish that they were inadequate.
- Article 33: Notification to the supervisory authority without undue delay and, where feasible, within 72 hours of the controller becoming aware, unless the breach is unlikely to create a risk to people's rights and freedoms.
- Article 34: Communication to affected people without undue delay when the breach is likely to create a high risk, subject to the article's exceptions.
The fine ceiling depends on the infringement established. Article 32 infringements fall within the €10 million or 2% of total worldwide annual turnover tier, whichever is higher; an independently established infringement of Article 5 principles can attract the €20 million or 4% tier. These are ceilings, not automatic penalties. Security architects should retain evidence of XSS controls, testing, and remediation to support the assessment. The GDPR text and CJEU judgment summary provide the legal basis.
Build the breach process on the current text. The Commission's Digital Omnibus proposal would extend the authority deadline to 96 hours and limit authority notification to breaches likely to result in a high risk. The Council kept both changes in the negotiating mandate it agreed on 21 October 2026, but the European Parliament has not yet adopted its position. As of November 2026, Articles 33 and 34 are unchanged.
SOC 2 trust criteria
For SaaS organizations pursuing SOC 2, the current criteria are the 2017 Trust Services Criteria with revised points of focus (2022):
| Trust Criteria | XSS Controls |
|---|---|
| CC6.1 | Logical access architecture limits what injected script can reach, for example session cookies marked HttpOnly |
| CC6.6 | Protection against threats from outside the system boundary, such as script payloads submitted through public inputs |
| CC7.1 | Vulnerability identification through SAST, browser-based DAST, and penetration testing |
| CC7.2 | Anomalies such as CSP violation reports are monitored and analyzed as potential security events |
Auditors will examine SAST/DAST integration, penetration test results, CSP implementation, and remediation evidence.
HIPAA considerations
Healthcare applications must protect PHI. When an XSS attack lets an unauthorized person acquire or view unsecured PHI, the HIPAA Breach Notification Rule presumes a breach unless the covered entity or business associate demonstrates, through a documented risk assessment, a low probability that the PHI was compromised. On the Security Rule side, the technical safeguards for access control and integrity (45 CFR 164.312(a) and (c)) apply to the application itself, protection from malicious software is an addressable implementation specification among the administrative safeguards (164.308(a)(5)(ii)(B)), and a known XSS finding belongs in the risk analysis and risk management required by 164.308(a)(1).
HHS proposed a substantial Security Rule update in January 2025, including explicit vulnerability scanning and penetration testing requirements. As of November 2026 no final rule has been published, so the current safeguards above are the ones that apply.
5. Security program integration
XSS prevention must be embedded in the software development lifecycle, not bolted on at the end.
Secure SDLC integration points
Requirements Phase: Security requirements specify output encoding standards and CSP requirements. Threat modeling identifies XSS risk in user-generated content features.
Design Phase: Architecture review validates data/presentation separation. Security architects approve any exceptions to JSON-only APIs. CSP policy is designed for the application.
Development Phase: IDE plugins flag dangerous patterns (dangerouslySetInnerHTML, innerHTML). Pre-commit hooks run SAST on changed files. Code review checklists include XSS verification.
Testing Phase: SAST tools scan for XSS patterns. DAST tools probe for injection vulnerabilities with browser-based scanning. Penetration testing includes manual XSS attempts.
Deployment Phase: Security gates block deployment with unresolved critical or high findings. CSP headers verified in staging. WAF rules updated for new endpoints.
Operations Phase: CSP violation reports monitored. WAF alerts reviewed. Incident response procedures address successful attacks.
Security gates
The application security metrics program describes the four gates, how to tune them, and how to measure what each one catches. Here we only add the XSS check each gate needs:
Gate 1: Pre-Commit
ESLint security rules block the commit when a dangerous pattern appears: an innerHTML assignment, or dangerouslySetInnerHTML outside the reviewed sanitization wrapper.
Gate 2: Pull Request
Security review is required for changes that touch sanitization components. PRs that modify CSP configuration are labeled automatically.
Gate 3: CI Pipeline
Dependency checks cover DOMPurify and the other sanitizer libraries, because a sanitizer bypass that was fixed upstream stays exploitable in every build that still ships the old version. The build fails if new critical or high XSS findings appear.
Gate 4: Pre-Production
DAST runs against the staging environment with a browser-based crawler, because DOM-based XSS only shows up when a browser engine executes the page.
Developer training
The training program itself, from onboarding and annual refreshers to hands-on exercises and effectiveness measurement, is laid out in the metrics program post. For XSS, the audience is every frontend and full-stack developer. The content should cover why encoding depends on the output context, why dangerouslySetInnerHTML and th:utext are acceptable only for content that has been sanitized, which reviewed wrapper to use for that, how DOM sources reach dangerous sinks, and what CSP does and does not stop. Capture-the-flag exercises should include XSS challenges.
6. Metrics and measurement
Security architects must demonstrate program effectiveness through metrics. MTTD, MTTR, vulnerability density, recurrence rate, gate effectiveness, exposure window, residual risk trend, and security debt ratio are defined in the application security metrics program, and XSS findings feed into them like any other vulnerability class. Two further measures are specific to XSS.
XSS-specific metrics
CSP Violation Rate
Monitor CSP violation reports. High volumes may indicate attempted attacks or application compatibility issues. Track trends over time.
Exception Rate
How often do teams request exceptions to XSS-related requirements (disabling CSP, bypassing sanitization)? High exception rates may indicate requirements that are too strict or inadequate tooling.
7. Incident response considerations
Despite prevention efforts, XSS attacks may succeed. The metrics program post covers the response lifecycle, from identification through lessons learned, and the communication templates for each stakeholder group. What follows is the part specific to XSS: the signals that reveal an attack and the steps the response has to include.
Detection indicators
XSS attacks may be detected through:
- CSP violation reports showing blocked inline script attempts
- WAF alerts for XSS patterns in requests
- Outbound requests from client browsers to unexpected hosts, reported as
connect-srcorform-actionviolations - User reports of unexpected behavior or content
- Stored payload discovery during content moderation
- Security researcher reports through bug bounty programs
Response procedures
Immediate Actions (First Hour)
Identify affected pages and user population. Preserve evidence (logs, CSP reports, payload samples). Consider emergency mitigations (stricter CSP, feature disable).
Short-Term Actions (First 24 Hours)
Identify the vulnerable code path and injection vector. Deploy emergency patch or disable vulnerable functionality. Assess data exposure scope. Invalidate potentially compromised sessions. Analyze stored payloads and remove or neutralize every stored copy, because a fixed render path does not protect other consumers of the same data. Start the breach assessments from section 4 at this point: the GDPR deadline runs from awareness of the breach, not from the end of the investigation.
Medium-Term Actions (First Week)
Review similar code patterns for the same vulnerability class. Update detection rules based on attack patterns. Notify affected users if credentials or sensitive data were exposed.
Long-Term Actions
Turn the injection pattern into a gate rule so the same sink cannot return unnoticed. Consider additional controls (stronger CSP, Trusted Types).
8. Organizational considerations
Security architecture exists within organizational context. Effective XSS prevention requires addressing human and process factors.
Security champions program
How to select, train, and use security champions is described in the metrics program post. For XSS specifically, champions ensure their teams understand when dangerouslySetInnerHTML is appropriate, review CSP changes, and catch common patterns like innerHTML usage or missing sanitization.
Third-party and vendor risk
XSS risk extends to third-party code:
- Do embedded widgets require
'unsafe-inline'in the CSP, weakening protection? - Do third-party JavaScript libraries have known XSS vulnerabilities?
- Do vendor-provided components properly sanitize user content?
- Do analytics or marketing scripts introduce XSS vectors?
Include XSS protection requirements in vendor security assessments. Monitor dependencies for vulnerabilities using tools like npm audit or Snyk.
Stakeholder communication
Different stakeholders require different messages:
For Developers: Technical depth, framework-specific guidance, code examples, and clear standards.
For Product Managers: Business risk context, user impact scenarios, and prioritization rationale.
For Executives: Business impact, regulatory implications, competitive positioning, and resource requirements framed in terms of risk reduction.
For Auditors: Control documentation, testing evidence, remediation tracking, and exception justification with compensating controls.
Wrapping Part 3
XSS prevention is not merely a coding problem. It is a security program challenge that spans architecture, governance, process, and culture.
Security architects must think beyond individual vulnerabilities to systemic controls. The goal is not to fix every XSS finding manually but to build systems where XSS cannot easily occur, is detected quickly when it does, and is remediated efficiently.
XSS defense reflects a maturity journey:
Developer perspective (Part 1 and Part 2): Understand the vulnerability mechanics and implement secure code patterns using framework-provided protections, sanitization libraries, and Content Security Policy.
Security architect perspective: Design controls, measure effectiveness, integrate security into organizational processes, and ensure compliance with regulatory requirements.
Organizations that master both perspectives build resilient applications that withstand current attacks and evolving threats. The technical foundations from Part 1 and Part 2 enable developers to write secure code. The architectural controls and XSS-specific measures here, built on the shared application security metrics program, ensure those practices are consistently applied, measured, and improved across the organization.
XSS has persisted for over two decades not because we lack technical solutions, but because consistent application of those solutions requires organizational commitment. The frameworks, tools, and patterns exist. The challenge is ensuring they are used correctly, everywhere, all the time.
About the author
20+ years in software development, now focused on application security. Writing hands-on guides on secure coding patterns, vulnerability analysis, and security architecture.
Comments
Join the discussionNo comments yet. Be the first to comment.
Cross-site Scripting
A practical guide to cross-site scripting in Java and React applications. Across this multipart series, explore reflected, stored, and DOM-based XSS, secure coding patterns, modern browser defenses, and the architectural decisions that help prevent XSS at scale.





