如果我使用@PreAuthorize方法级安全性,则不会调用@Valid

时间:2017-04-11 22:35:25

标签: spring spring-mvc spring-boot spring-security

以下是我的控制器的代码段:

@RestController
@RequestMapping(Constants.REST_CONTROLLER_ENDPOINT)
class ProductRestController {

private final ProductValidator productValidator;
@InitBinder
private void initBinder(WebDataBinder binder) {
    binder.setValidator(productValidator);
}

private Product createProductFromJson(Product input) {
    ...
    return product;
}

@PasswordFilter
@RequestMapping(consumes = { Constants.HAL_CONTENT_TYPE,
       Constants.JSON_CONTENT_TYPE }, method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<Product> createProduct(@RequestBody @Validated Product input) {
    Product product = createProductFromJson(input);
    Product savedProduct = productRepository.save(product);
    return new ResponseEntity<>(product, responseHeaders, HttpStatus.CREATED);
}

@PasswordFilter
@PreAuthorize("@productRestController.validatePermission(authentication, #product)")
@RequestMapping(value = "/{id}", consumes = { Constants.JSON_CONTENT_TYPE }, method = {
        RequestMethod.PUT })
@ResponseStatus(HttpStatus.OK)
public ResponseEntity<Product> updateProduct(Principal principal, @PathVariable Long id,
        @RequestBody @Validated Product product) {
       ...
    return new ResponseEntity<>(updatedProduct, HttpStatus.OK);
}

未在createProduct方法中调用@Validated。 如果我对@PreAuthorize发表评论,则会在createProduct方法中调用@Validated。注释甚至不在createProduct方法上,所以我不确定这是否与@InitBinder有关。

这是一个SpringBoot 1.4.1应用程序。我正在使用mockmvc @SpringBootTest来测试此方法

1 个答案:

答案 0 :(得分:0)

事实证明,@InitBinder方法需要公开才能调用验证:

@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setValidator(productValidator);
}