【问题标题】:Spring Security @PreAuthorize - Restrict certain roles by using Spring ELSpring Security @PreAuthorize - 使用 Spring EL 限制某些角色
【发布时间】:2012-12-25 10:42:06
【问题描述】:

使用 Spring Security 3.1.3.RELEASE

因此,如果有一个角色列表(超过 10 个)并且需要阻止只有一个角色访问 Spring Controller 方法。这可以使用 Spring 表达式语言来完成,并且避免列出每个非常受欢迎的角色吗?

例如,通过包含 Not 符号。

@PreAuthorize("!hasRole('ROLE_FREE_USER')")

这样列出所有角色

@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_PAID_USER','ROLE_PREM_USER',...)

我看过这里的文档:http://static.springsource.org/spring-security/site/docs/3.0.x/reference/el-access.html

但是 NOT EQUAL to case 上似乎没有任何内容。有人遇到类似问题吗?

【问题讨论】:

标签: spring spring-mvc spring-security


【解决方案1】:

我很确定 Spring 表达式语言 (SPEL) 支持非符号 (!)。自然,它会返回 boolean 结果。

来自official documentation 的示例:

// evaluates to false
boolean falseValue = parser.parseExpression("!true").getValue(Boolean.class);

// -- AND and NOT --
String expression =  "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')";
boolean falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);

【讨论】:

【解决方案2】:

在这种情况下,Spring 表达式语言对我不起作用。最初我尝试了以下方法,

@RequestMapping("/post/edit")
        @PreAuthorize("hasRole('ROLE_OWNER') AND !hasRole('ROLE_ADMIN')")
        public String editPost(Model model, Principal principal,  HttpServletRequest request, @RequestParam("postId") String postId) {
    }

但是,我必须从方法内部重新检查角色并重定向页面,以防用户拥有管理员权限。

@RequestMapping("/post/edit")
    @PreAuthorize("hasRole('ROLE_OWNER')")
    public String editPost(Model model, Principal principal,  HttpServletRequest request{

        //Admin Users does not have access to post edit page
        if (request.isUserInRole("ROLE_ADMIN")) {
            return TemplateNamesConstants.POST_WALL;
        }
}

如果您找到更好/替代的解决方案,请更新此线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-26
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    相关资源
    最近更新 更多