【问题标题】:Does Spring Security have a 'hasAllRole' that performs the AND version of 'hasAnyRole'Spring Security 是否具有执行“hasAnyRole”的 AND 版本的“hasAllRole”
【发布时间】:2011-12-19 16:19:16
【问题描述】:

我在 Grails 中使用 Spring Security 来限制对我的控制器的访问。我有一个用例,我想检查用户是否分配了多个角色。我意识到我可以制作另一个与“人有这两个角色”同义的角色,但这需要比我想要的更多的改变。

Spring Security 有一个 OR 版本 expression 来检查用户是否具有任何角色列表:

//allow user to access if he has role ROLE_ADMIN -OR- ROLE_USER
//note this is shortcut notation for hasAnyRole(["ROLE_ADMIN","ROLE_USER"])
@Secured(["ROLE_ADMIN","ROLE_USER"])
def index = {}

有没有一种方法,或者只是使用Spring Expression Language (SpEL) 来执行以下操作:

//allow user to access if he has role ROLE_ADMIN -AND- ROLE_USER
@Secured("hasAllRole(['ROLE_ADMIN','ROLE_USER']")
def index = {}

注意:SpringSecurityUtils 类确实有方法

public static boolean ifAllGranted(final String roles)

【问题讨论】:

    标签: spring grails spring-security spring-el


    【解决方案1】:
    hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')
    

    再简单不过了

    【讨论】:

    • 您确定@Secured 支持该语法吗?
    • OP链接的文档显示要使用的注释是PreAuthorize。
    • 但我希望,它不适用于@Secured。它的 Java Doc 和我发现的所有示例都直接使用角色,但没有表达式!
    • 确实如此。我假设 OP 能够找到适当的注释,因为他知道在文档中查找的位置。
    • 在给出答案时,您可能不应该做出这样的假设。我认为最好提到它对@Secured 不起作用,因为这是所提出问题的核心部分。
    【解决方案2】:

    如果你使用@PreFilter 而不是@Secured 那么你可以这样写:

    @PreFilter("hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')")
    

    【讨论】:

      【解决方案3】:

      你不能不hasRole('ROLE_ADMIN') and hasRole('ROLE_USER')吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-06-06
        • 2023-02-23
        • 1970-01-01
        • 2018-04-05
        • 1970-01-01
        • 2014-09-03
        • 2015-02-23
        相关资源
        最近更新 更多