Mass assignment in Spring: how one JSON field makes someone an admin
Binding request bodies straight to JPA entities lets clients set fields you never meant to expose: roles, verification flags, account ids. How mass assignment happens in Spring, and the request-DTO pattern that removes it, plus the response-side twin of the bug.
The “Edit profile” form has two fields: name and bio. The controller behind it looks like this:
@PatchMapping("/users/me")
User update(@RequestBody User changes, @AuthenticationPrincipal Jwt jwt) {
User user = users.findBySubject(jwt.getSubject()).orElseThrow();
BeanUtils.copyProperties(changes, user, "id");
return users.save(user);
}
The User entity has twelve fields. Among them: role, emailVerified, accountId, creditLimit. The form doesn’t show them, but the endpoint doesn’t know about the form. It knows about User, and Jackson will set any field the client sends. So a user opens their browser’s developer tools, edits the request, adds "role": "ADMIN", and the server saves it.
That’s mass assignment: binding client input to an object with more writable properties than the client should control. It became famous in 2012, when a researcher used a mass assignment bug in a Rails app to add his key to the Rails organisation on GitHub. OWASP’s current API Security Top 10 folds it into risk number three, broken object property level authorization, together with its twin, which I’ll come to below.
Spring makes this easy to write by accident, so let’s make it impossible instead.


Why it’s so easy to write
- Entities are convenient. They already have every field, getters and setters. Using them as request bodies saves writing another class.
- The danger is invisible in review. The vulnerable controller above contains nothing that looks wrong. The bug is in the difference between what the entity has and what the form shows, and that difference lives in two different files.
- It gets worse over time. Someone adds
isBetaTesterordiscountPercentto the entity next year. It’s instantly writable through every endpoint that binds the entity, and nobody touched those endpoints.
Fix 1: one request DTO per use case
The request body type should list exactly the fields this operation lets the client change, and nothing else:
public record ProfileUpdate(
@Size(max = 80) String name,
@Size(max = 500) String bio) {}
@PatchMapping("/users/me")
ProfileView update(@Valid @RequestBody ProfileUpdate changes, @AuthenticationPrincipal Jwt jwt) {
User user = users.findBySubject(jwt.getSubject()).orElseThrow();
user.updateProfile(changes.name(), changes.bio());
return ProfileView.from(users.save(user));
}
“Update profile” and “admin changes a user’s role” are different use cases, so they get different DTOs and different endpoints, with different authorization. The admin endpoint can have a role field; the profile endpoint simply can’t express it.
Records are a good fit: they’re short, immutable, and there’s no temptation to add “just one more” setter.
Fix 2: reject unknown fields
By default, Spring Boot configures Jackson to ignore properties it doesn’t recognise. With a DTO, "role": "ADMIN" is then silently dropped, which is safe, but it hides the attempt and hides client bugs. I prefer to reject it:
@JsonIgnoreProperties(ignoreUnknown = false)
public record ProfileUpdate(String name, String bio) {}
Or globally for request bodies:
spring:
jackson:
deserialization:
fail-on-unknown-properties: true
Now the request fails with a 400, your logs show someone sending fields that don’t exist, and clients that misspell a field find out immediately instead of wondering why their change didn’t stick. (If you turn it on globally, check that response parsing for third-party APIs uses its own ObjectMapper, since you usually do want to ignore unknown fields from someone else’s API.)
Fix 3: map explicitly, never copy wholesale
BeanUtils.copyProperties, ModelMapper with default settings, and “merge the request into the entity” helpers all have the same flaw: they copy whatever matches by name. Even with a DTO, a later change that adds a matching field to both classes reopens the hole.
Write the mapping by hand, or put it on the entity as a method that names the operation:
@Entity
class User {
// …
void updateProfile(String name, String bio) {
if (name != null) this.name = name;
if (bio != null) this.bio = bio;
}
}
It’s a few more lines. It’s also the only version where reading the code tells you exactly what a client can change.
Fix 4: the twin bug, on the way out
The same convenience causes the opposite problem in responses. Return the entity, and Jackson serialises every field: passwordHash, failedLoginCount, internalNotes, the account relationship and everything it pulls in. OWASP used to list this separately as excessive data exposure; now it’s the other half of the same risk.
The fix is symmetrical: a response DTO per view (ProfileView, AdminUserView), built explicitly. As a bonus, you stop loading lazy relationships by accident during serialisation, and your API stops changing shape whenever someone refactors the entity.
Fix 5: form binding has the same problem
Server-rendered forms bound with @ModelAttribute have the same issue: any request parameter that matches a property gets bound. If you can’t switch to a dedicated form object, restrict binding explicitly:
@InitBinder("user")
void allowOnlyProfileFields(WebDataBinder binder) {
binder.setAllowedFields("name", "bio");
}
An allowlist, never a denylist. A denylist (setDisallowedFields("role")) is out of date the day someone adds isBetaTester.
Test the attack, not just the feature
@Test
void profileUpdateCannotChangeRole() throws Exception {
mvc.perform(patch("/users/me")
.with(jwt().jwt(j -> j.subject("bob")))
.contentType(APPLICATION_JSON)
.content("""
{"name": "Bob", "role": "ADMIN"}
"""))
.andExpect(status().isBadRequest());
assertThat(users.findBySubject("bob").orElseThrow().getRole()).isEqualTo(Role.USER);
}
The second assertion matters: it checks the outcome, not just the status code.
Checklist
| Do | Instead of |
|---|---|
| A request DTO per operation | @RequestBody on an entity |
fail-on-unknown-properties: true for request bodies |
Silently ignoring extra fields |
| Explicit mapping, or an entity method per operation | copyProperties, auto-mappers, generic merge |
| A response DTO per view | Returning entities |
setAllowedFields for form binding |
setDisallowedFields |
| A test that sends a forbidden field | Testing only the fields the form shows |
Takeaways
- Binding requests to entities makes every settable field client-writable, including ones added next year.
- Use one request DTO per use case, listing only the writable fields, and reject unknown fields.
- Map explicitly; wholesale copying reopens the hole the moment two classes share a field name.
- Use response DTOs too, or the same convenience leaks fields on the way out.
- Test the attack: send
"role": "ADMIN"and assert nothing changed.