Spring Security + MVC:相同的@RequestMapping,不同的@Secured [英] Spring Security + MVC : same @RequestMapping, different @Secured

查看:100
本文介绍了Spring Security + MVC:相同的@RequestMapping,不同的@Secured的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我们有一个使用Spring MVC和Spring Security配置的API端点.我们希望能够处理成对的@RequestMapping和@Secured批注,其中唯一的@Secured批注值在成对之间是不同的.这样,我们将能够根据同一请求的安全规则返回不同的响应主体.

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
    }
}

我们如何实现这一目标? 如果可以做到这一点:应该如何为同时具有ROLE_A和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 ?

推荐答案

假定您将Spring 3.1(或更高版本)与RequestMappingHandlerMapping(和RequestMappingHandlerAdapter)一起使用,则可以扩展请求映射机制.您可以通过创建自己的

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.

您将需要在RequestMappingHandlerMapping上覆盖"getCustomMethodCondition"方法,并根据该方法和@Secured注释的存在来构造您的RequestCondition的自定义实现.在将传入请求与方法进行匹配时,所有这些信息都将被考虑在内.

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.

相关答案(尽管不是特定于@Secured注释,但机制相同)也可以找到此处

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

这篇关于Spring Security + MVC:相同的@RequestMapping,不同的@Secured的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆