GuardAPI Logo
GuardAPI

Fix Mass Assignment in Spring Boot

Mass Assignment is a critical vulnerability where an attacker manipulates the HTTP request to bind data to internal object fields they shouldn't have access to. In Spring Boot, this typically happens when developers use JPA entities directly as method parameters in controllers. If your 'User' entity has a 'role' or 'isAdmin' field, a malicious POST request can overwrite these values, leading to full privilege escalation.

The Vulnerable Pattern

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserRepository userRepository;
@PutMapping("/{id}")
public User updateProfile(@PathVariable Long id, @RequestBody User user) {
    // CRITICAL VULNERABILITY: Spring binds the entire JSON payload to the User entity.
    // An attacker can send {"isAdmin": true} in the body to escalate privileges.
    return userRepository.save(user);
}

}

The Secure Implementation

The fix is simple: Decouple your persistence layer from your API layer. By using Data Transfer Objects (DTOs), you create a strict 'allow-list' of fields that can be modified by the user. If a field isn't in the DTO, the Jackson deserializer won't bind it, and your business logic won't process it. As a secondary defense, you can use '@JsonProperty(access = JsonProperty.Access.READ_ONLY)' on sensitive entity fields, but DTOs are the industry standard for robust AppSec.

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserRepository userRepository;
@PutMapping("/{id}")
public ResponseEntity<User> updateProfile(@PathVariable Long id, @RequestBody UserUpdateDTO dto) {
    User existingUser = userRepository.findById(id).orElseThrow();
    
    // Explicitly map only allowed fields from the DTO to the Entity
    existingUser.setDisplayName(dto.getDisplayName());
    existingUser.setBio(dto.getBio());
    
    return ResponseEntity.ok(userRepository.save(existingUser));
}

}

// Use a dedicated DTO to define the allow-list of fields public class UserUpdateDTO { private String displayName; private String bio; // Getters and Setters only for these two fields }

System Alert • ID: 8071
Target: Spring Boot API
Potential Vulnerability

Your Spring Boot API might be exposed to Mass Assignment

74% of Spring Boot apps fail this check. Hackers use automated scanners to find this specific flaw. Check your codebase before they do.

RUN FREE SECURITY DIAGNOSTIC
GuardLabs Engine: ONLINE

Free Tier • No Credit Card • Instant Report

Verified by Ghost Labs Security Team

This content is continuously validated by our automated security engine and reviewed by our research team. Ghost Labs analyzes over 500+ vulnerability patterns across 40+ frameworks to provide up-to-date remediation strategies.