GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Dropwizard

In Dropwizard, XSS typically manifests when an API reflects unsanitized user input while using an insecure 'Content-Type' or failing to set 'X-Content-Type-Options'. If a browser sniffs the response as HTML, it's game over. To secure this, we must enforce strict JSON serialization and hard-coded security headers.

The Vulnerable Pattern

@Path("/user")
public class UserResource {
    @GET
    @Path("/echo")
    @Produces(MediaType.TEXT_HTML) // Vulnerability: Browser will execute scripts
    public String echo(@QueryParam("name") String name) {
        return "

Welcome, " + name + "

"; // Vulnerability: Unsanitized reflection } }

The Secure Implementation

The fix involves three layers of defense. First, we switch from 'text/html' to 'application/json', ensuring the browser treats the payload as data. Second, we let Jackson handle the serialization of our Map/DTO, which automatically escapes characters that could break JSON structure. Finally, we implement a 'ContainerResponseFilter' to add 'X-Content-Type-Options: nosniff', preventing the browser from ignoring the JSON type and executing the content as HTML, and a strict CSP to kill any potential execution dead.

@Path("/user")
@Produces(MediaType.APPLICATION_JSON) // Fix 1: Force JSON
public class UserResource {
    @GET
    @Path("/echo")
    public Response echo(@QueryParam("name") String name) {
        Map data = new HashMap<>();
        data.put("message", "Welcome, " + name);
        return Response.ok(data).build(); // Fix 2: Data is now JSON-encoded
    }
}

// Fix 3: Global Security Header Filter public class SecurityFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) { response.getHeaders().add(“X-Content-Type-Options”, “nosniff”); response.getHeaders().add(“Content-Security-Policy”, “default-src ‘none’; frame-ancestors ‘none’;”); } }

System Alert • ID: 7109
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.