Fix XSS in API Responses in Spring Boot
API XSS is the silent killer. Devs assume JSON protects them, but misconfigured headers or 'clever' response wrappers turn a REST endpoint into a drive-by exploit delivery system. If your API reflects input and the browser can be tricked into rendering it as HTML via MIME-sniffing or explicit Content-Type headers, you're pwned.
The Vulnerable Pattern
@GetMapping("/user/profile")
public String getProfile(@RequestParam String bio) {
// VULNERABLE: Returns raw string with default or text/html content type
// An attacker can pass bio=
return "User Bio: " + bio + "";
}
The Secure Implementation
The exploit relies on the browser interpreting the API response as HTML. To kill this: 1. Always use @RestController or @ResponseBody to ensure data is serialized (usually via Jackson) into JSON, which browsers won't execute as script. 2. Explicitly set 'X-Content-Type-Options: nosniff' to prevent browsers from ignoring the 'application/json' header and 'guessing' that the response is HTML. 3. If you absolutely must return HTML, use the OWASP Java HTML Sanitizer to whitelist safe tags and attributes before reflecting input.
@RestController
@RequestMapping("/api")
public class ProfileController {
@GetMapping("/user/profile")
public ResponseEntity
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.
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.