Defensive Programming can be very easy with Symfony HttpClient

Published: (February 28, 2026 at 01:37 PM EST)
1 min read
Source: Dev.to

Source: Dev.to

Problem

If your app lets users submit URLs that you then fetch—for link previews, webhooks, or RSS feeds—you have a serious security problem waiting to happen. An attacker can submit something like http://127.0.0.1/admin or http://169.254.169.254 (AWS metadata endpoint) and your server will happily fetch it. This is a Server‑Side Request Forgery (SSRF) attack.

Solution

Symfony provides a built‑in solution: NoPrivateNetworkHttpClient. It decorates your existing HTTP client and blocks requests to private IP ranges (or any ranges you configure).

Before

getPayload()
            ->getString('url');

        $response = $this->client
            ->request('GET', $url);

        return new JsonResponse(
            $response->getContent()
        );
    }
}

After

safeClient = new NoPrivateNetworkHttpClient($client);
    }

    #[Route('/api/preview', methods: ['POST'])]
    public function preview(
        Request $request,
    ): JsonResponse {
        $url = $request->getPayload()
            ->getString('url');

        $response = $this->safeClient
            ->request('GET', $url);

        return new JsonResponse(
            $response->getContent()
        );
    }
}

NoPrivateNetworkHttpClient is a decorator, so you simply wrap your existing client—no other code changes are required. Consult the Symfony documentation to configure the specific IPs or IP ranges you want to disallow.

If you fetch user‑submitted URLs and aren’t using this decorator, you should start doing so.

Watch the explanation on YouTube.

0 views
Back to Blog

Related posts

Read more »

Country codes and regional differences

Supporting Kosovo with Symfony Intl Symfony’s Intl component does not include Kosovo because its ISO 3166‑1 code XK is a user‑assigned code, not an official on...