Java – spring security MVC: same @ requestmapping, different @ secured
Suppose we have an API endpoint configured using spring MVC and spring security We want to be able to handle @ requestmapping and @ secured annotation pairs, where the unique @ secured annotation value is different from the pairing In this way, we can return different response bodies according to the security rules of the same request
This may make our code easier to maintain by avoiding checking security rules directly into the method body
There is an abnormal example. Here is what we want 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 it? If you can do this: how to create a_ A and role_ User management priority of B?
Solution
Assuming you are using spring 3.1 (or later) and requestmappinghandlermapping (and requestmappinghandleradapter), you can extend the request mapping mechanism You can implement this by creating your own implementation of the requestcondition interface, and extend requestmappinghandlermapping according to the @ secured annotation of your method to build this structure
You will need to override the "getcustommethodcondition" method on requestmappinghandlermapping and construct a custom implementation of your requestcondition based on the existence of the method and @ secured annotation When matching incoming requests to methods, all information is considered
The relevant answers (although not specific to the @ secured annotation, but the mechanism is the same) can also be found here or here