SECURITY ENGINEERING · PART 8 · WRITING SECURE CODE · CODE · 112 OF 229

Secure Coding in Java and Spring Security

Java and Spring give you strong security building blocks, but the defaults and the common patterns still leave gaps. This episode covers the mistakes that appear most in Spring Boot code review: SQL and injection, unsafe deserialization, SSRF, mass assignment, broken method-level authorization, actuator and CORS misconfiguration, secrets in properties, and the Spring Security patterns that fix each, with short code.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 9
  9. 10
  10. 11
  11. 12
  12. 13
  13. 14
  14. 15
  15. 16
  16. 17
  17. 18
  18. 19
  19. 20
  20. 21
  21. 22
  22. 23
  23. 24
  24. 25
  25. 26
  26. 27
  27. 28
  28. 29
  29. 30
  30. 31
  31. 32
  32. 33
  33. 34
  34. 35
  35. 36
  36. 37
  37. 38
  38. 39
  39. 40
  40. 41
  41. 42
  42. 43
  43. 44
  44. 45
  45. 46
  46. 47
  47. 48
  48. 49
  49. 50
  50. 51
  51. 52
  52. 53
  53. 54
  54. 55
  55. 56
  56. 57
  57. 58
  58. 59
  59. 60
  60. 61
  61. 62
  62. 63
  63. 64
  64. 106
  65. 107
  66. 108
  67. 109
  68. 110
  69. 111
  70. 112
  71. 113
  72. 114
  73. 115
  74. 116
  75. 117
  76. 118
  77. 119
  78. 120
  79. 121
  80. 122
  81. 123
  82. 124
  83. 125
  84. 126
  85. 127
  86. 128
  87. 129
  88. 130
  89. 131
  90. 132
  91. 133
  92. 134
  93. 135
  94. 136
  95. 137
  96. 138
  97. 139
  98. 140
  99. 141
  100. 142
  101. 143
  102. 144
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • Parameterise JPA
  • DTOs not entities
  • @PreAuthorize with ownership
  • block SSRF and unsafe deser
  • secure Actuator

Notes

Injection in JPA

First, injection. People assume an ORM like JPA makes injection impossible; it does not. Concatenating user input into a JPQL or native query is just as injectable as raw SQL. The fix is the same as last episode: bound parameters, with named parameters in Spring Data or positional ones in native queries. Two extra Java traps: dynamic ORDER BY or column names from user input cannot be bound as parameters, so validate them against an allowlist, and the Criteria API or QueryDSL is safer for dynamic queries.

queries, right and wrong
// WRONG: concatenated JPQL
"from User where name = '" + n + "'"

// RIGHT: bound parameter
@Query("from User where name = :n")
User find(@Param("n") String n);

// native queries: still use ?1,
// never string-build. Avoid
// dynamic sort/column from input

Unsafe deserialization

Unsafe deserialization is the most Java-specific entry on this list. Deserializing attacker-controlled bytes with native Java serialization can lead to remote code execution through gadget chains in libraries on the classpath. Never call readObject on untrusted data. For JSON, keep Jackson's polymorphic default typing off, because it lets an attacker choose which class to instantiate. For XML, disable external entity resolution on every parser to prevent XXE, which reads server files and reaches internal services.

Deserialization
  • native Java serialization of untrusted data = remote code execution (gadget chains)
  • never readObject() on untrusted bytes
  • JSON: avoid polymorphic type handling from input (Jackson default typing off)
  • XML: disable external entities (XXE) on every parser

SSRF

Server-side request forgery, or SSRF, is increasingly the highest-impact web bug, especially in the cloud. Your server fetches a URL the user supplied, for a webhook, an image, a PDF or an import, and an attacker points it at internal services or the cloud metadata endpoint to steal credentials. The fix is to allowlist the hosts and schemes you will fetch, resolve the DNS and check the resulting address is not private or link-local, and disable redirects. Never fetch an arbitrary user-supplied URL.

Server-side request forgery
  • user supplies a URL; the server fetches it
  • attacker targets internal services, cloud metadata (169.254.169.254), localhost
  • fix: allowlist hosts and schemes, resolve DNS and check the IP, block private ranges, no redirects
  • applies to webhooks, image fetch, PDF render, imports

Mass assignment

Mass assignment, also called over-posting, is common in Spring. You bind the request body directly onto a JPA entity for convenience. An attacker adds a field you never intended to accept, such as role equals admin or a balance, and because the entity has that field, Spring binds it. The fix is to bind to a data transfer object that contains only the fields a client may set, then map it to the entity explicitly in your code. Never bind requests straight onto your persistence entities.

Mass assignment / over-posting
  • binding the request body straight onto a JPA entity
  • attacker adds "role":"ADMIN" or "balance":99999 and it is bound
  • fix: bind to a DTO with only the allowed fields
  • map DTO -> entity explicitly
  • never expose entities directly in controllers

Authorization

Authorization is where most real Spring findings live. Authenticate in the filter chain, but enforce authorization at the method too, with PreAuthorize. Crucially, check ownership, not just role: a user with the right role can still reach another user's record if you only check role, the insecure direct object reference problem. Configure the chain to deny by default and open specific paths, not permit everything and block the sensitive ones. And write negative authorization tests.

Spring Security authz
  • secure the URL in the filter chain AND the method: @PreAuthorize("hasRole('ADMIN')")
  • @PreAuthorize("#id == authentication.name")
  • enforce ownership, not just role (stops IDOR)
  • deny by default: lock down, then open specific paths
  • test authz with negative tests

Config footguns

A cluster of configuration footguns. Actuator endpoints are powerful; never expose env, heapdump or mappings to the internet, and secure the rest. For CORS, do not combine a wildcard origin with credentials, and list only trusted origins. For CSRF, keep Spring's protection for cookie-session apps; disabling it for a purely stateless token API is reasonable if you know why. And turn off detailed error stack traces in production so you do not leak internals.

Spring Boot configuration
  • Actuator: never expose env, heapdump or mappings; restrict and secure it
  • CORS: no "*" with credentials; list origins
  • CSRF: keep it for cookie- session apps; off is fine for stateless token APIs
  • no error stack traces in production

Secrets and dependencies

Two problems live around your code, not in it. Secrets: never put database passwords or API keys in application dot properties or in git. Inject them at runtime from environment variables or a secrets manager, which Part twelve covers. And dependencies: two of the worst recent Java vulnerabilities, Log4Shell and Spring4Shell, were in dependencies, not application code. Run software composition analysis in the pipeline and keep Spring Boot and libraries current.

Around the code
  • secrets: never in application.properties or git; use env vars or a vault, inject at runtime
  • dependencies: Log4Shell and Spring4Shell were dependency issues; run SCA (OWASP Dependency-Check, Snyk) and patch
  • keep Spring Boot current

Validation in Spring

Tie it back to validation. Spring supports Bean Validation with annotations on DTOs: not blank, size limits, email format, numeric ranges. Put at valid on the controller parameter and Spring enforces them, returning a clean error when input is malformed. This gives server-side allowlist validation declaratively, where input enters the app. Combine it with last episode's output defenses, parameterised queries and auto-escaping, for both halves of injection defense.

Bean Validation
public record CreateUser(
  @NotBlank @Size(max=50)
  String name,
  @Email String email,
  @Min(0) @Max(150) int age) {}

// @Valid on the controller param
public X create(@Valid @RequestBody
  CreateUser body) { ... }

Common mistakes

The recurring findings, in one place. Concatenated JPQL or native SQL. Binding requests straight to entities, allowing mass assignment. Role checks with no ownership check, allowing one user to read another's data. Deserializing untrusted data, or leaving Jackson default typing on. SSRF from fetching user-supplied URLs. Actuator endpoints or error stack traces exposed to the internet. And secrets in application dot properties or committed to git. If you review for just these, you catch most Spring security bugs.

Avoid these
  • concatenated JPQL or native SQL
  • binding requests to entities (mass assignment)
  • role checks without ownership checks (IDOR)
  • deserializing untrusted data; Jackson default typing
  • SSRF on user-supplied URLs
  • Actuator or stack traces exposed; secrets in config

Say it like this

In the interview: Spring Security that denies by default, with method-level PreAuthorize including ownership checks, not just roles, to prevent insecure direct object references. I bind to DTOs not entities to stop mass assignment, use Bean Validation and parameterised JPA. I avoid unsafe deserialization, keep Jackson default typing off, allowlist server-side URL fetches against SSRF, keep secrets in a vault, scan dependencies, and lock down Actuator.

In the interview
  • "Deny-by-default Spring
  • Security, method-level
  • @PreAuthorize with ownership
  • checks, DTOs not entities, Bean Validation, parameterised
  • JPA, no unsafe
  • deserialization, SSRF
  • allowlists, secrets in a vault, SCA on dependencies, and Actuator locked down."

Interview questions

Q1Can you have SQL injection when using JPA or Hibernate?

Yes. Concatenating user input into JPQL or native queries is injectable despite the ORM. Use bound named or positional parameters, validate any dynamic column or sort values against an allowlist, and prefer the Criteria API or QueryDSL for dynamic queries.

Q2What is unsafe deserialization in Java?

Converting attacker-controlled bytes into objects, especially with native Java serialization, which can trigger gadget chains in classpath libraries and lead to remote code execution. Avoid readObject on untrusted data and keep Jackson polymorphic default typing disabled.

Q3What is mass assignment in Spring?

Binding a request body directly onto a persistence entity, so an attacker can set fields that were never meant to be client-controlled, such as a role or balance. The fix is to bind to a DTO containing only allowed fields and map it to the entity explicitly.

Q4How do you prevent SSRF in a Spring application?

When the server fetches a user-supplied URL, allowlist permitted hosts and schemes, resolve the DNS and verify the resolved IP is not private, loopback or link-local (blocking the cloud metadata endpoint), disable redirects, and never fetch arbitrary URLs.

Q5How does method-level authorization work in Spring Security?

Annotations such as @PreAuthorize evaluate an expression before a method runs, for example checking a role or that a resource belongs to the current principal. Enforcing ownership, not just role, at the method prevents insecure direct object reference vulnerabilities.

Q6Why should Spring Boot Actuator be secured?

Actuator exposes operational endpoints that can reveal configuration, environment variables, heap dumps and mappings. Exposing them publicly leaks secrets and internals, so they should be restricted to internal networks and protected with authentication.

Q7When should you disable CSRF protection in Spring Security?

CSRF protection matters for applications that authenticate with cookies or sessions and should stay enabled there. It can reasonably be disabled for stateless APIs that authenticate with bearer tokens on each request, since those are not vulnerable to classic CSRF.

Q8How do you validate input in Spring Boot?

Use Bean Validation annotations such as @NotBlank, @Size, @Email, @Min and @Max on DTOs and apply @Valid on controller parameters, so Spring enforces server-side allowlist validation and returns errors for malformed input at the point it enters the application.