Can Spring Security Use @PreAuthorize On Spring Controllers Methods?


Answer :

Yes, it works fine.

You need <security:global-method-security pre-post-annotations="enabled" /> in ...-servlet.xml. It also requires CGLIB proxies, so either your controllers shouldn't have interfaces, or you should use proxy-target-class = true.


See Spring Security FAQ (emphasis mine).

In a Spring web application, the application context which holds the Spring MVC beans for the dispatcher servlet is often separate from the main application context. It is often defined in a file called myapp-servlet.xml, where “myapp” is the name assigned to the Spring DispatcherServlet in web.xml. An application can have multiple DispatcherServlets, each with its own isolated application context. The beans in these “child” contexts are not visible to the rest of the application. The “parent” application context is loaded by the ContextLoaderListener you define in your web.xml and is visible to all the child contexts. This parent context is usually where you define your security configuration, including the element). As a result any security constraints applied to methods in these web beans will not be enforced, since the beans cannot be seen from the DispatcherServlet context. You need to either move the declaration to the web context or moved the beans you want secured into the main application context.

Generally we would recommend applying method security at the service layer rather than on individual web controllers.

If you apply pointcuts to service layer you only need to set <global-method-security> in your app's security context.


If you're using Spring 3.1, you can do some pretty cool stuff with this. Take a look at https://github.com/mohchi/spring-security-request-mapping. It's a sample project that integrates @PreAuthorize with Spring MVC's RequestMappingHandlerMapping so that you can do something like:

@RequestMapping("/") @PreAuthorize("isAuthenticated()") public String authenticatedHomePage() {     return "authenticatedHomePage"; }  @RequestMapping("/") public String homePage() {     return "homePage"; } 

A request for "/" will call authenticatedHomePage() if the user is authenticated. Otherwise it will call homePage().


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?