Cross-site scripting (XSS)

Encode untrusted values for their output context to prevent script execution in the browser.

Description

XSS occurs when a web application handles untrusted input incorrectly while generating a page, allowing malicious script to run in the user's browser.

Potential impact

  • Malicious script may steal user data or bypass application protections.
  • Sensitive page data or script-accessible cookies may be exposed. HttpOnly cookies do not by themselves stop actions performed with the victim's permissions.
  • An attacker may execute arbitrary code within the browser context.

Remediation

  • Encode values at the final output step for the actual context, such as HTML text, attributes or JavaScript. HTML text escaping does not replace JavaScript encoding or URL validation. Prefer auto-escaped templates where possible.
  • Use Content Security Policy (CSP) to restrict script execution as an additional defense.
  • Adding Spring Security does not automatically encode user input. If HTML input is required, sanitize it with a reviewed allow-list policy.

Examples

These Spring controller excerpts assume that the response is rendered as HTML. HtmlUtils refers to org.springframework.web.util.HtmlUtils; the encoding below applies to an HTML text position.

Before

java
// Before
@RequestMapping("/welcome")
@ResponseBody
public String welcomeMessage(@RequestParam String username) {
    // Insert input directly into HTML
    return "<h1>Welcome, " + username + "!</h1>";
}

After

java
// After
@RequestMapping("/welcome")
@ResponseBody
public String welcomeMessage(@RequestParam String username) {
    // Encode input for HTML text
    String safeUsername = HtmlUtils.htmlEscape(username);
    return "<h1>Welcome, " + safeUsername + "!</h1>";
}

Explanation:

  • Before: Inserts username directly into HTML. Input containing malicious script may execute in the browser.
  • After: Uses HtmlUtils.htmlEscape to encode the input as HTML text. In this position, input markup is displayed as text instead of executing.

Related CVEs

References