How to Prevent XSS and SQL Injection in Spring: A Practical Guide
This article explains the dangers of XSS and SQL injection attacks, demonstrates realistic attack scenarios, and provides a comprehensive backend solution using Spring AOP, HttpMessageConverter, custom Servlet Filters, request wrappers, and ESAPI to sanitize inputs and protect web applications.
XSS Cases
Many developers are aware of Cross‑site scripting (XSS) but often underestimate its impact. The article presents two illustrative attacks where an attacker crafts malicious URLs that trigger script execution, steal cookies, and impersonate users.
Cross‑site scripting (XSS) is a common web security vulnerability that allows attackers to inject client‑side scripts into pages viewed by other users, bypassing same‑origin policies and potentially exposing sensitive data.
Case 1
A malicious user (Mallory) discovers an XSS flaw on Bob's site, crafts a URL containing a <script>…</script> payload, sends it via email, and steals Alice's authentication cookie, enabling account takeover.
Case 2
Shows typical SQL injection examples where user input like 105 OR 1=1 or 105; DROP TABLE Suppliers can retrieve all records or delete tables.
Solution Overview
The article focuses on backend defenses (the second layer of protection) and proposes three main approaches:
Frontend form validation (basic first line of defense).
Backend data filtering and replacement.
Persistent‑layer encoding standards (e.g., MyBatis).
The detailed implementation uses Spring components.
Spring AOP
Attempting to apply AOP to all API entry points is problematic because RESTful APIs have diverse parameter types (GET query parameters, POST bodies), making a unified AOP solution difficult.
HttpMessageConverter
By extending MappingJackson2HttpMessageConverter and overriding readInternal, JSON request bodies can be intercepted for sanitization, though this method cannot handle GET requests.
Servlet Filter
A custom GlobalSecurityFilter implements javax.servlet.Filter (or extends OncePerRequestFilter) to inspect and clean request parameters, headers, and bodies. The filter registers a GlobalSecurityRequestWrapper that reads the original input stream, stores it as a string, and provides overridden methods: getInputStream() – returns a sanitized stream. getReader() – reads the sanitized body. getParameter(), getParameterValues(), getHeader() – apply XSS stripping.
Sanitization is performed by stripXSS, which uses ESAPI's canonicalize and a set of regular‑expression patterns to remove script tags, event handlers, JavaScript URLs, etc.
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
// ... read body, apply stripXSS, then continue filter chain
}Handling Request Body
Because ESAPI's default javaScriptCodec corrupts JSON strings, a custom encoder is built that only includes HTMLEntityCodec and PercentCodec. The method stripXSSRequestBody uses this encoder to safely canonicalize JSON payloads before pattern replacement.
SQL Injection Mitigation
For parameter values, stripXSSSql employs ESAPI's encodeForSQL with a MySQL codec to neutralize injection attempts.
Multipart Requests
The filter skips sanitization for multipart/form-data requests, delegating file‑upload handling to other mechanisms.
ESAPI Integration
Instructions for adding ESAPI to a project via Gradle or Maven are provided, along with the required ESAPI.properties and validation.properties files.
Soul‑Searching Questions
Do you understand the Java decorator design pattern and where it appears in frameworks?
Why is validating only a file’s extension insufficient?
Have you watched "The Matrix"? (just for fun)
These questions encourage readers to think deeper about security design.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
