如何使用<sec:authorize access ="hasRole('ROLES)">来检查多个角色?

K. *_*ddy 43 java spring spring-mvc spring-security

我想基于使用Spring Security JSP标记库的角色有条件地显示一些内容.但在Spring Security 3.1.x中只检查一个角色.

我可以使用,但ifAllGranted已被弃用.

有帮助吗?

dim*_*mas 78

spring security中有一个特殊的安全表达式:

hasAnyRole(角色列表) - 如果已授予用户指定的任何角色(以逗号分隔的字符串列表给出),则为true.

我从来没有使用它,但我认为这正是你要找的.

用法示例:

<security:authorize access="hasAnyRole('ADMIN', 'DEVELOPER')">
    ...
</security:authorize>
Run Code Online (Sandbox Code Playgroud)

以下是参考文档链接,其中描述了标准的spring安全表达式.另外,这里是一个讨论,我在下面描述了如何在需要时创建自定义表达式.

  • 在第二个问题上,您应该能够将'hasRole'与'and'运算符一起使用,例如hasRole('ADMIN')和hasRole('DEVELOPER')来实现此功能. (4认同)

小智 5

@dimas的答案在逻辑上与你的问题不一致; ifAllGranted不能直接替换hasAnyRole.

Spring Security 3-> 4迁移指南:

旧:

<sec:authorize ifAllGranted="ROLE_ADMIN,ROLE_USER">
    <p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>
Run Code Online (Sandbox Code Playgroud)

新(SPeL):

<sec:authorize access="hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')">
    <p>Must have ROLE_ADMIN and ROLE_USER</p>
</sec:authorize>
Run Code Online (Sandbox Code Playgroud)

更换ifAllGranted直接hasAnyRole会导致春季,以评估使用该语句OR的代替AND.也就是说,如果经过身份验证的主体包含至少一个指定的角色,则hasAnyRole返回,而Spring(现在已经不推荐使用Spring Security 4)方法仅在经过身份验证的主体包含所有指定角色时返回.trueifAllGrantedtrue

TL; DR:要复制ifAllGranted使用Spring Security Taglib的新身份验证表达式语言的行为,需要使用该hasRole('ROLE_1') and hasRole('ROLE_2')模式.