How to make @PreAuthorize having higher precedence than @Valid or @Validated
I had the same issue and I found this post. The comment of M. Deinum helps me to understand what was going wrong
Here is what I did :
- The public method has the @PreAuthorize and do the check
- There is NO @Valid on the @RequestBody parameter
- I create a second method, private, where I do the DTO validation. Using the @Valid annotation
- The public methods delegates the call to the private one. The private method is called only is the public method is authorized
Example :
@RequestMapping(method = RequestMethod.POST)
@PreAuthorize("hasRole('MY_ROLE')")
public ResponseEntity createNewMessage(@RequestBody CreateMessageDTO createMessageDTO) {
// The user is authorized
return createNewMessageWithValidation(createMessageDTO);
}
private ResponseEntity createNewMessageWithValidation(@Valid CreateMessageDTO createMessageDTO) {
// The DTO is valid
return ...
}