How to fix XSS in API Responses
in NancyFX
Executive Summary
NancyFX, while legacy, is still found in various .NET stacks. XSS in API responses occurs when user-controlled input is reflected back into the response body without proper encoding or, more commonly, when the 'Content-Type' is incorrectly set to 'text/html' instead of 'application/json'. This allows a browser to interpret the payload as an active script rather than data.
The Vulnerable Pattern
Get["/api/user/{id}"] = parameters => {
var userId = parameters.id;
// VULNERABLE: Direct string concatenation and manual content-type setting to HTML
return Response.AsText("{\"status\": \"error\", \"message\": \"User " + userId + " not found\"}", "text/html");
};
The Secure Implementation
The vulnerability lies in treating an API response as HTML. By returning 'text/html', an attacker can pass a payload like '' as the ID, which the browser executes. The fix involves two steps: First, use 'Response.AsJson()', which automatically sets the 'Content-Type' to 'application/json' and prevents the browser from sniffing the response as HTML. Second, always use an object serializer rather than manual string concatenation to ensure special characters are properly escaped within the JSON structure.
Get["/api/user/{id}"] = parameters => {
var userId = (string)parameters.id;
// SECURE: Use Response.AsJson to enforce application/json and proper serialization
return Response.AsJson(new {
status = "error",
message = $"User {userId} not found"
}, Nancy.HttpStatusCode.NotFound);
};
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.