【问题标题】:Spring Security @PreAuthorize - Restrict certain roles by using Spring ELSpring Security @PreAuthorize - 使用 Spring EL 限制某些角色
【发布时间】:2012-12-25 10:42:06
【问题描述】:
【问题讨论】:
标签:
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;
}
}
如果您找到更好/替代的解决方案,请更新此线程。