Spring安全性:@PreAuthorize仅与@RequestMapping一起使用


问题内容

我有一个Spring MVC控制器,想用Spring Method Security来保护它。

在以下示例中, 它可以工作 - @RequestMapping@PreAuthorize注释相同的方法:

@Controller
public class MyController {

    @RequestMapping(value = "/test", method = {RequestMethod.POST, RequestMethod.GET})
    @PreAuthorize("isAuthenticated()")
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {  
        return test(request, response);
    }

    public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ...
    }

在此示例中, 它不起作用 - @RequestMapping@PreAuthorize注释了不同的方法:

@Controller
public class MyController {

    @RequestMapping(value = "/test", method = {RequestMethod.POST, RequestMethod.GET})
    public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {  
        return test(request, response);
    }

    @PreAuthorize("isAuthenticated()")
    public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ...
    }

这种奇怪行为的原因可能是什么?


问题答案:

在第二个示例中,test直接从该handleRequest方法调用该方法。Spring没有机制来拦截来自同一类中with的方法调用。因此,@PreAutorize永远不会调用Proxy
/ AOP方法的开始。

有关Spring Proxy的更多信息