Fix SSRF (Server Side Request Forgery) in Spring Boot
SSRF in Spring Boot environments typically manifests when RestTemplate, WebClient, or java.net.URL are weaponized to reach internal metadata services (169.254.169.254), internal databases, or bypass VPC firewalls. If your application accepts a URL from a user and fetches it without strict validation, you are providing a pivot point for attackers to map your internal architecture.
The Vulnerable Pattern
@RestController public class ProxyController { @Autowired private RestTemplate restTemplate;@GetMapping("/view-image") public byte[] getImage(@RequestParam String url) { // CRITICAL VULNERABILITY: User-controlled URL is passed directly to RestTemplate // An attacker can pass 'http://169.254.169.254/latest/meta-data/' return restTemplate.getForObject(url, byte[].class); }
}
The Secure Implementation
Fixing SSRF requires a 'Deny by Default' posture. First, parse the input string into a URI object to prevent basic obfuscation bypasses. Second, implement a strict allowlist for schemes (only HTTPS) and hostnames. To prevent DNS Rebinding, the host should be resolved to an IP address and checked against internal/private IP ranges (RFC 1918) before the request is dispatched. For robust defense, use a custom ClientHttpRequestFactory that validates the target IP at the socket level during the connection phase.
@RestController public class SecureProxyController { private static final ListALLOWED_DOMAINS = Arrays.asList("trusted-cdn.com", "api.partner.com"); @GetMapping("/view-image") public byte[] getImage(@RequestParam String url) throws URISyntaxException { URI uri = new URI(url); String host = uri.getHost(); String scheme = uri.getScheme(); // 1. Enforce HTTPS only if (!"https".equalsIgnoreCase(scheme)) { throw new SecurityException("Insecure protocol"); } // 2. Strict Domain Allowlisting if (host == null || !ALLOWED_DOMAINS.contains(host.toLowerCase())) { throw new SecurityException("Unauthorized destination host"); } // 3. Use the validated URI object, not the raw string RestTemplate restTemplate = new RestTemplate(); return restTemplate.getForObject(uri, byte[].class); }
}
Your Spring Boot API
might be exposed to SSRF (Server Side Request Forgery)
74% of Spring Boot 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.