Search code examples
javaspringspring-mvcspring-securityspring-annotations

Spring Security: @PreAuthorize works only together with @RequestMapping


I have a Spring MVC controller and want to secure it with Spring Method Security.

In the following example it works - @RequestMappingand @PreAuthorizeannotate the same method:

@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 {
        ...
    }

In this example it does not work - @RequestMappingand @PreAuthorizeannotate different methods:

@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 {
        ...
    }


What might be the reason for this strange behaviour?


Solution

  • In the second example the test method is being called directly from the handleRequest method. Spring has no mechanism to intercept method calls from with in the same class. Thus, the Proxy / AOP method inception for @PreAutorize is never invoked.

    More on the topic of Spring Proxy