Spring Security + MVC : same @RequestMapping, different @Secured

java, spring, spring-mvc, spring-security

Solution

Assuming you are using Spring 3.1 (or up) together with the RequestMappingHandlerMapping (and RequestMappingHandlerAdapter) you can extend the request mapping mechanism. You can do this by creating your own implementation of the RequestCondition interface and extend the RequestMappingHandlerMapping to construct this based on the @Secured annotation on your method.

You would need to override the 'getCustomMethodCondition' method on the RequestMappingHandlerMapping and based on the Method and the existence of the @Secured annotation construct your custom implementation of the RequestCondition. All that information is then taken into account when matching incoming requests to methods.

Related answers (although not specific for @Secured annotations but the mechanism is the same) is also to be found here or here

Problem

Let say we have an API endpoint configured using Spring MVC and Spring Security. We would like to be able to handle pairs of @RequestMapping and @Secured annotations where the only @Secured annotation values differ from pair to pair. This way, we would be able to return a different response body depending on security rules for the same request. This may allow our code to be more maintainable by avoiding to check for security rules directly into the method body. With a not working example, here is what we would like to do : ``` @Controller @RequestMapping("/api") public class Controller { @Secured ({"ROLE_A"}) @RequestMapping(value="{uid}", method=RequestMethod.GET) @ResponseBody public Response getSomething(@PathVariable("uid") String uid) { // Returns something for users having ROLE_A } @Secured ({"ROLE_B"}) @RequestMapping(value="{uid}", method=RequestMethod.GET) @ResponseBody public Response getSomethingDifferent(@PathVariable("uid") String uid) { // Returns something different for users having ROLE_B } } ``` How can we achieve this ? And if this can be done: How the priority should be managed for a user who has both ROLE_A and ROLE_B ?

Original source

Related problems