【问题标题】:Access/check Spring Security hierarchical roles programmatically以编程方式访问/检查 Spring Security 分层角色
【发布时间】:2012-03-14 08:22:54
【问题描述】:

在我的 Grails 项目中,我使用 Spring Security 插件定义了多个 hierarchical roles,例如ROLE_USER > SOME_OTHER_ROLE。当使用 @Secured 注释保护控制器方法时,它工作得很好。但是,我也想在我的代码中以编程方式检查一个用例的角色。使用以下方法,即使用户通过分层角色定义继承角色,我也总是得到 false

request.isUserInRole('SOME_OTHER_ROLE')

此外,以下调用永远不会直接返回继承的角色:

SecurityContextHolder.context?.authentication?.authorities
springSecurityService.getPrincipal().getAuthorities()

有没有办法检查用户是否也有继承的角色?

【问题讨论】:

    标签: grails spring-security


    【解决方案1】:

    这似乎是SecurityContextHolderAwareRequestWrapper 中的一个错误(或至少是一个遗漏),它添加了一个请求包装器来实现isUserInRole 方法。

    您可以使用roleVoter bean 的extractAuthorities 方法。为其添加依赖注入(def roleVoter),然后调用

    def allRoles = roleVoter.extractAuthorities(
            SecurityContextHolder.context.authentication)
    

    【讨论】:

    • 谢谢,伯特!奇迹般有效。我很快就会为此开张票。
    • 这是 Jira ticket 供 Spring Security 供将来参考。
    猜你喜欢
    • 2014-12-26
    • 2017-10-31
    • 2018-09-01
    • 2019-12-19
    • 2014-05-01
    • 2012-12-01
    • 2017-10-19
    • 2021-12-21
    • 1970-01-01
    相关资源
    最近更新 更多