GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Spring WebFlux

Think APIs are immune to XSS? Wrong. If your WebFlux functional endpoints or controllers reflect unsanitized input while mismanaging Content-Type headers, you're handing an execution primitive to any attacker. In reactive stacks, the danger often lies in manual string concatenation within Mono/Flux streams and 'magic' content-type sniffing. Here is how to lock down your reactive streams.

The Vulnerable Pattern

@GetMapping("/welcome")
public Mono welcome(@RequestParam String user) {
    // VULNERABLE: Direct reflection of user input into a string
    // If a browser sniffs this as HTML,  executes.
    return Mono.just("Welcome back, " + user + "");
}

The Secure Implementation

The exploit vector relies on the browser interpreting the API response as HTML. To mitigate this in Spring WebFlux: 1. Use HtmlUtils.htmlEscape() to neutralize meta-characters like <, >, and ". 2. Explicitly set the 'Content-Type' to 'application/json' whenever possible, as browsers won't execute scripts in JSON contexts. 3. Always include the 'X-Content-Type-Options: nosniff' header to prevent MIME-sniffing attacks. 4. Implement a strict Content Security Policy (CSP) to block unauthorized inline scripts.

@GetMapping("/welcome")
public Mono> welcome(@RequestParam String user) {
    // SECURE: HTML Escape the input and explicitly set headers
    String safeUser = org.springframework.web.util.HtmlUtils.htmlEscape(user);
    return Mono.just(ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML_VALUE)
        .header("X-Content-Type-Options", "nosniff")
        .header("Content-Security-Policy", "default-src 'self'")
        .body("Welcome back, " + safeUser + ""));
}
System Alert • ID: 8129
Target: API Responses API
Potential Vulnerability

Your API Responses API might be exposed to XSS

74% of API Responses apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.