GuardAPI Logo
GuardAPI

Fix XSS in API Responses in Symfony

XSS in APIs occurs when an endpoint reflects untrusted input in a response without enforcing the correct Content-Type or escaping. In Symfony, if you manually construct a Response instead of using the dedicated JsonResponse, browsers may 'sniff' the content as HTML, allowing an attacker to execute arbitrary JavaScript in the context of your domain. A proper fix requires strict MIME type enforcement and proper encoding of the output buffer.

The Vulnerable Pattern

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

public function search(Request $request): Response { $query = $request->query->get(‘q’); // VULNERABLE: Manual string concatenation and missing Content-Type header // Browser might interpret this as text/html if it contains tags return new Response(”{‘status’: ‘error’, ‘message’: ‘Invalid query: ” . $query . ”’}”); }

The Secure Implementation

The vulnerable code uses the generic Response class, which defaults to text/html if not specified. An attacker passing ?q= could trigger XSS if the browser's MIME-sniffing logic overrides the missing header. The secure implementation uses JsonResponse, which enforces 'Content-Type: application/json' and runs the data through json_encode, neutralizing HTML tags. To harden this further at the infrastructure level, ensure your Symfony security headers include 'X-Content-Type-Options: nosniff' to prevent browsers from interpreting JSON as HTML regardless of the payload.

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

public function search(Request $request): JsonResponse { $query = $request->query->get(‘q’); // SECURE: JsonResponse automatically sets Content-Type to application/json // and uses json_encode to properly escape data return new JsonResponse([ ‘status’ => ‘error’, ‘message’ => ‘Invalid query: ’ . $query ], JsonResponse::HTTP_BAD_REQUEST); }

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