【问题标题】:Spring Security hasRole() for Unauthenticated Users, Considering Role HierarchySpring Security hasRole() 用于未经身份验证的用户,考虑角色层次结构
【发布时间】:2019-12-03 02:23:03
【问题描述】:

我的 Spring Boot 2 + Spring Security 应用程序中有一个角色层次结构:

@Bean
public RoleHierarchy roleHierarchy() {
    var rh = new RoleHierarchyImpl();
    rh.setHierarchy("ROLE_ADMIN > ROLE_USER and ...");

    return rh;
}

现在我(作为管理员)想代表另一个用户创建一个实体,但我应该检查该用户是否具有基于上述层次结构的特定权限。

我知道当前经过身份验证的用户可以call spring security hasRole(),但就我而言,我要授权的用户未经过身份验证。

现在,我可以检查用户是否具有该特定权限:

public boolean hasAuthority(User user, String authority) {
    return user.getAuthorities()
            .stream()
            .anyMatch(grantedAuthority -> grantedAuthority.getName().equals(authority));
}

但是这样会忽略相当长的层次结构。

如果有任何帮助,我将不胜感激。

【问题讨论】:

    标签: java spring spring-boot spring-security


    【解决方案1】:

    您可以使用角色层次结构,请参阅RoleHierarchy#getReachableGrantedAuthorities

    Collection<? extends GrantedAuthority> getReachableGrantedAuthorities(Collection<? extends GrantedAuthority> authorities) 
    

    返回所有可访问权限的数组。

    可访问权限是直接分配的权限加上角色层次结构中可(传递)访问的所有权限。

    示例: 角色层次结构:ROLE_A > ROLE_B 和 ROLE_B > ROLE_C。
    直接分配权限:ROLE_A。
    可访问权限:ROLE_A、ROLE_B、ROLE_C。

    参数:

    authorities - 直接分配的权限列表。

    返回:

    给定指定权限的所有可访问权限列表。

    您修改后的代码:

    public boolean hasAuthority(User user, String authority) {
        return roleHierarchy()
            .getReachableGrantedAuthorities(user.getAuthorities())
            .stream()
            .anyMatch(grantedAuthority -> grantedAuthority.getName().equals(authority));
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-30
      • 2013-10-23
      • 2013-10-31
      • 2017-08-05
      • 2016-02-13
      • 1970-01-01
      • 2016-01-03
      • 2012-12-01
      • 2020-10-20
      相关资源
      最近更新 更多