wasAsked.

How do you prevent over-posting and insecure object binding in a Spring Boot REST API?

Zoho · Full Stack Developer · 3-4-years · technical

Published

Year not specified · Java, Spring Boot, Authentication & Security

Community answers

Posted by wasAsked editorial collection

Over-posting (mass assignment) happens when request JSON is bound directly onto an entity or rich object, letting clients set fields they should not control. Vulnerable example @PutMapping("/users/{id}") public User update(@PathVariable Long id, @RequestBody User user) { user.setId(id); return userRepository.save(user); // client can send "role":"ADMIN" or "balance":100000 } Fixes 1. Dedicated request DTOs per operation (records work well) public record UpdateProfileRequest(@NotBlank @Size(max = 100) String displayName, @Size(max = 500) String bio) { } Only allowed fields exist, so extra JSON properties have nowhere to go. 2. Load the entity and apply changes explicitly @PutMapping("/users/me") public ProfileDto update(@AuthenticationPrincipal Jwt jwt, @Valid @RequestBody UpdateProfileRequest req) { User user = userRepository.findById(userId(jwt)).orElseThrow(); user.setDisplayName(req.displayName()); user.setBio(req.bio()); return mapper.toDto(user); // saved by the transaction (dirty checking) } Mapping libraries such as MapStruct are fine if you explicitly ignore sensitive targets (@Mapping(target = "role", ignore = true)) and use separate mappers for different operations. 3. Reject unknown properties spring.jackson.deserialization.fail-on-unknown-properties=true (or @JsonIgnoreProperties(ignoreUnknown = false)) makes unexpected fields a 400 error instead of being silently ignored, which also helps detect client bugs. 4. Restrict form binding for MVC endpoints For form submissions bound with @ModelAttribute, use @InitBinder with setAllowedFields to allow-list bindable fields (Spring's data binding has had security advisories around unrestricted binding, so allow-listing is the safer pattern). 5. Authorization on every object - Server-controlled fields — owner, role, tenant, prices, status transitions, audit timestamps — are set by business logic only. - Check ownership: users may update only their own resources (method security with @PreAuthorize, or explicit checks), returning 404 or 403 otherwise. This prevents IDOR. 6. Response DTOs too Never return entities directly; response DTOs prevent leaking password hashes or internal flags. 7. PATCH safety For JSON Merge Patch or JSON Patch, apply changes to a DTO, validate it, then map to the entity; restrict patchable paths. Testing: integration tests sending extra fields (role, ownerId, balance) and asserting they are rejected or ignored.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics