Search code examples
springspring-bootspring-security

Why is WebDataBinder used when Jackson is/should be used for deserialization (which breaks correct order of validation/authorization)?


My original requirement is that I want to use @EnableMethodSecurity, but when I call @RestController method with invalid payload and user missing required role, the validation takes precedence. So instead of getting 403/401 I'm getting 400 revealing something about unauthorized endpoint. That's incorrect.

I found out, that in my case it's because validation isn't part of AOP proxy chain, but it's triggered by org.springframework.web.method.support.InvocableHandlerMethod#invokeForRequest inside depths of call getMethodArgumentValues.

The workaround(well if it's even workaround) here is straightforward. Disable the validator for WebDataBinder and annotate the controller with @Validated. Doing so the binder won't throw MethodArgumentNotValidException and bean validation will be called correctly by spring in response to processing annotation @Validated.

My first question is: 1. why is WebDataBinder even used if I'm using jackson library for deserialization? Or am I? Well at least I'd like to and expect it to be used. Is there some mistake? I don't know if it's correct, I think I saw some notice, that it should not be used...

minimal working example(check master branch)

Excerpts from MWE(I can publish it later, I'm missing some tests yet):

Controller class:

@RestController
@RequestMapping("/someController")
public class SomeController {

    //    @RolesAllowed(ROLE1)
    @RolesAllowed(ROLE2)
    @PostMapping("search")
    public String contactSearch(@Valid @RequestBody SearchRequest searchRequest) {
        return "OK";
    }

    @NoArgsConstructor
    @AllArgsConstructor
    @Getter
    @Setter
    public static class SearchRequest {

        @NotNull
        @PositiveOrZero
        private Long userId;

    }

app/security definition:

@SpringBootApplication
@EnableWebSecurity
@EnableMethodSecurity
public class IsWebBinderUsedToBindJacksonDtoRequestBodyApplication {

    public static final String ROLE1 = "ROLE1";
    public static final String ROLE2 = "ROLE2";

    public static void main(String[] args) {
        SpringApplication.run(IsWebBinderUsedToBindJacksonDtoRequestBodyApplication.class, args);
    }

    @Bean
    public UserDetailsService userDetailsService() {
        // Define an in-memory user with roles
        UserDetails user1 = User.withDefaultPasswordEncoder()
                .username("user1")
                .password("password")
                .roles(ROLE1)
                .build();

        UserDetails user2 = User.withDefaultPasswordEncoder()
                .username("user2")
                .password("password")
                .roles(ROLE2)
                .build();

        return new InMemoryUserDetailsManager(user1, user2);
    }

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                .csrf(AbstractHttpConfigurer::disable)
                .authorizeHttpRequests(a -> a.anyRequest().permitAll())
                .httpBasic(conf -> conf.realmName("aaa"))
                .build();
    }
}

disabling of validation can be done using:

@InitBinder
public void initUserBinder(WebDataBinder binder) {
    //no validation whatsoever!
    binder.setExcludedValidators(e->true);
}

and I have the second question about this @InitBinder. If there isn't better way and I have to use this, how do I configure WebDataBinder globally to disable the validator as shown (or provide some benevolet Validator implementation, or to do any other customization)? I kinda cannot find the solution for springboot 3.


Solution

  • I'm not sure if this behavior is intentional or not, or whether the binder should be used or not in this case. But I saw several threads asking for fixing this without any response, so I will add my here.

    The cause of problem is binder calling the validation of input data before calling authorization proxy for method level validation( here: org.springframework.web.method.support.InvocableHandlerMethod#invokeForRequest), as demonstrated in minimal working example.

    One possible solution is to use @Validated to enable spring validation using AOP proxy and either disable binder validation using @InitBinder or globally using advice:

    @ControllerAdvice
    @Slf4j
    @AllArgsConstructor
    public final class BinderShouldNotValidateAdvice {
    
        //global disabling data binder premature validation
        @InitBinder
        public void initUserBinder(WebDataBinder binder) {
            // customization specific to binding a User
            binder.setExcludedValidators(e->true);
        }
    
    }
    

    It does not seem, that spring handles ConstraintViolationException automatically. It will fail producing stacktrace to log and http 500 in response without failure description. So you need to implement your own exception handler as shown in MWE as well.

    This is just one potential solution, if someone know better one, please let me know. Thank you!