Spring Security:@PreAuthorize仅与@RequestMapping一起使用

时间:2016-11-28 14:59:00

标签: java spring spring-mvc spring-security spring-annotations

我有一个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 {
        ...
    }


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

1 个答案:

答案 0 :(得分:3)

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

More on the topic of Spring Proxy