@PreAuthorize Controller invalidates @Inject in @InitBinder

我与影子孤独终老i 提交于 2019-12-24 17:21:57

问题


In a simple controller :

@PreAuthorize("hasAuthority('USER')")
@Controller
@RequestMapping("/test")
public class TestController {

  private Logger logger = LoggerFactory.getLogger(getClass());

  @Inject
  private MyValidator myValidator;

  @InitBinder("myObj")
  private void initBinder(WebDataBinder binder) {
    logger.info("myValidator = {}", myValidator);
    binder.initDirectFieldAccess();
    binder.setValidator(myValidator);
  }

  @RequestMapping(value = "/doPost", method = RequestMethod.POST)
  public String doPost(MyObj myObj , BindingResult br ) throws IOException {
    logger.info("myObj = {} , bindingResult = {}" , myObj , br);
    return "redirect:/test/form";
  }
}

I noticed the injected validator is always null in the initBinder method , the logger is even null (and throws NPE) , this is weird.

If I totally remove the @InitBinder initBinder() method , the myValidator is available (not null) again in each method.

After eliminating many factors , I found the culprit is the @PreAuthorize("hasAuthority('USER')") . After removing this @PreAuthorize , everything works fine.

Is it a bug ? Does something conflicts with SpringSecurity and SpringValidation and SpringMVC ?

How to fix it ?

environments :

<spring.version>4.2.1.RELEASE</spring.version>
<springboot.version>1.3.0.M5</springboot.version>
<spring-security.version>4.0.2.RELEASE</spring-security.version>

Thanks in advanced.


回答1:


The easiest solution was to create a setter method for myValidator. this setter is then called when the app initializes. Do this for all the injectables that are being nullified by @PreAuthorize tags.



来源:https://stackoverflow.com/questions/33174428/preauthorize-controller-invalidates-inject-in-initbinder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!