All posts

How to Fix Xss Vulnerability in Java

Fix Xss Vulnerability in your Java app. Understand the root cause and apply the right solution.

XSS Vulnerabilities in Java

Java web applications face XSS through JSP expressions, Thymeleaf templates, or REST API responses that include unescaped user input.

How XSS Occurs

  • JSP <%= %> expressions not encoding output
  • Thymeleaf th:utext (unescaped text) with user data
  • REST responses including HTML from user input

The Fix

Use framework-provided escaping and add CSP headers:

import org.owasp.encoder.Encode;

@Controller
public class CommentController {

    @PostMapping("/comments")
    public String addComment(@RequestParam String content, Model model) {
        // Encode for HTML context
        String safeContent = Encode.forHtml(content);
        model.addAttribute("comment", safeContent);
        return "comment";
    }

    // REST API: encode in response
    @PostMapping("/api/comments")
    @ResponseBody
    public Map<String, String> addApiComment(@RequestBody CommentRequest req) {
        String safe = Encode.forHtml(req.getContent());
        commentService.save(safe);
        return Map.of("content", safe);
    }
}

// Security config
@Configuration
public class SecurityConfig {
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http.headers(h -> h
            .contentSecurityPolicy(csp -> csp
                .policyDirectives("default-src 'self'; script-src 'self'"))
            .xssProtection(Customizer.withDefaults())
        ).build();
    }
}

Use OWASP Java Encoder for context-specific encoding and always set Content-Security-Policy headers.

Avoiding Recurrence

Once you fix this error, add a regression test that reproduces the exact scenario. Document the root cause in your team's knowledge base so others can recognize the pattern. Configure monitoring alerts for early detection if the issue appears again in a different part of the codebase.

Bugsly for Java

Bugsly tracks suspicious input patterns that look like XSS attempts, helping your security team monitor and respond to attack patterns.

Try Bugsly Free

AI-powered error tracking that explains your bugs. Set up in 2 minutes, free forever for small projects.

Get Started Free