Web attacks and the OWASP Top 10: MITM, SQL injection, XSS, CSRF, DDoS
Five classic attacks seen from a Java backend: how they work and where the defenses belong (mTLS and replay protection, PreparedStatement and an ORDER BY allowlist, output encoding and nonce-based CSP, SameSite and CSRF tokens, rate limiting), the OWASP Top 10:2025 mapped to Spring Security 7, prompt injection in apps that call an LLM, and how to review AI-written security code.
On this page
1. The problem
A login form builds SQL by concatenation: username ' OR 1=1 -- matches 4 of 4 users and logs in without a password. In the same app, a comment containing <script> runs on every viewer's machine, admins included. Functional tests stay green.
2. Key idea
Every attack is a place where code trusts the wrong thing. The worst case is data interpreted as commands.
| Attack | What the code wrongly trusts | Main defense |
|---|---|---|
| SQL injection | input is only data | bind ?; whitelist column names, ORDER BY |
| XSS | data printed on a page is just text | encode on output; strict CSP nonce as a second layer |
| CSRF | an attached cookie means the user meant to send it | CSRF token + SameSite |
| MITM, replay | nobody is in the middle, a request arrives once | check certificates; mTLS or sign + timestamp + nonce |
| DDoS | traffic is always normal | L3/L4 to a provider; L7 rate limits |
| Prompt injection | content fed to an LLM is only data | treat it as untrusted, least-privilege tools |
2.1 Which defense, where?
| Defense | Use when | Don't use when |
|---|---|---|
| CSRF token | cookie or Basic auth logins | pure bearer-token APIs |
| Rate limit before password hashing | login, search, export | L3/L4 floods |
| Signed requests + timestamp + nonce | APIs between two backends |
2.2 Common traps
HttpOnlyonly blocks reading the cookie. An XSS script can stillfetchwithcredentials: 'include'.- A CSRF 403, a PKIX error or a CORS preflight failure means fix the caller, not disable the protection.
requestMatchersmatch in order:/api/**permitAll before/api/admin/**means the admin rule is never checked.- The login endpoint is the cheapest DoS target: each password hash costs ~100 ms of CPU.
3. In Java
// SQL: values bound with ?, identifiers through a whitelist
static final Map<String, String> SORTABLE = Map.of("name", "username", "created", "created_at");
String column = SORTABLE.get(sort);
if (column == null) throw new IllegalArgumentException("unsupported sort: " + sort); // 400
jdbc.query("SELECT username FROM users WHERE id = ? ORDER BY " + column, mapper, id);
// sort = "username; DROP TABLE users" -> 400; ' OR 1=1 -- -> 0 rows
// Spring Security 7: keep CSRF, deny by default
http.csrf(Customizer.withDefaults())
.authorizeHttpRequests(a -> a
.requestMatchers("/api/admin/**").hasRole("ADMIN") // specific first
.requestMatchers("/login", "/css/**").permitAll()
.anyRequest().authenticated());Templates: Thymeleaf th:text encodes; th:utext doesn't. Other languages: Go's html/template encodes per context; Node.js pg binds with $1.
Stopping replay between two backends
TLS stops a man in the middle if the client checks certificates. Real risks: code that disables certificate checks, TLS terminating at the load balancer, TLS not knowing who the client is. Between two backends use mTLS or sign requests with HMAC over method, path, timestamp, nonce and body.
A signature doesn't stop a valid request being resent. Also sign a timestamp (reject skew over 5 minutes) and a nonce (remembered only within that window). Check order: timestamp (cheap) → signature (MessageDigest.isEqual, constant time) → store the nonce atomically (SET nonce 1 NX EX 600). Storing the nonce before checking the signature lets an attacker burn a real client's nonces.
4. Working with AI
Give the AI: attack tests (' OR 1=1 --, <script>, cross-site POST without a token, resent requests), dependency scans, a draft CSP header.
Check in AI-written code:
- No SQL/JPQL concatenates values with
+;ORDER BYand column names go through a whitelist. - No
th:utext,innerHTMLordangerouslySetInnerHTMLwith user data. - No
csrf.disable()while logins still use cookies. - No disabled certificate checks, no CORS
*with credentials. - The last rule is
anyRequest().denyAll()or.authenticated().
5. Exercises
Exercise 1: An AI-written comments controller
A formLogin app with session cookies. The AI notes "fixed the AJAX form's 403; the query uses JdbcTemplate so it's safe":
@GetMapping("/products/{id}/comments")
String list(@PathVariable long id, @RequestParam(defaultValue = "created_at") String sort, Model model) {
model.addAttribute("comments", jdbc.queryForList(
"SELECT author, body FROM comment WHERE product_id = " + id + " ORDER BY " + sort));
return "comments"; // the template prints body with th:utext to keep line breaks
}
// SecurityConfig: http.csrf(c -> c.disable())Find the vulnerabilities and fix them.
Solution to Exercise 1
| Vulnerability | Why | Fix |
|---|---|---|
SQL injection via sort |
concatenated into ORDER BY; password_hash can be extracted char by char |
whitelist, unknown values get 400; bind id with ? |
| Stored XSS | th:utext runs <script> on the admin's machine |
th:text + CSS white-space: pre-line |
| CSRF | cookies with CSRF off: another site posts comments as the victim | turn it back on, send the token in an X-CSRF-TOKEN header |
Together they make a self-spreading XSS worm. The original 403 meant CSRF was working correctly.
Exercise 2: Two replay defenses
A partner calls POST /partner/orders with an HMAC signature. The AI offers: (A) each request carries a "request id", stored on arrival before the signature check; (B) sign a timestamp and nonce, check the timestamp, then the signature, then store the nonce. Pick one and say what changes with three instances.
Solution to Exercise 2
Pick B. A must remember every id forever (no time window), and storing the id before checking the signature lets an attacker burn a real client's ids. With three instances the nonce store moves to Redis SET NX EX. Add a key_id header so keys can rotate without downtime.
Summary
- Bind every value; whitelist column names and
ORDER BY. - Encode on output per context;
HttpOnlydoesn't stop XSS. - Disable CSRF only for pure bearer-token APIs.
- Replay defense: timestamp → signature → nonce.
- OWASP Top 10 sets priorities, ASVS is for verification.
Read more: Prompt injection and LLM application security.
Practice interview questions on this topic
- What is SQL injection, how do you prevent it, and where can it still happen with PreparedStatement?
- How do XSS and CSRF differ, and how does CSP help against XSS?
- How does CSRF work, and when is it okay to disable CSRF in Spring Security?
- What's in the OWASP Top 10, and how do you apply it to a Spring Boot project?
- A user changes /orders/123 to /orders/124 and sees someone else's order: what's the bug and the fix?
- How do you prevent replay on webhooks/partner APIs and rotate signing secrets without downtime?
Comments
Community rules