如何从RoleHierarchyImpl获取所有角色

时间:2011-10-16 03:31:30

标签: spring-security

我有一个角色层次结构配置和工作:

<beans:bean id="roleHierarchy"
    class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <beans:property name="hierarchy">
        <beans:value>
            ROLE_ADMIN > ROLE_PRIVILEGED
            ROLE_PRIVILEGED > ROLE_USER
            ROLE_USER > ROLE_ANONYMOUS
        </beans:value>
    </beans:property>
</beans:bean>

对于用户角色设置,我需要访问我定义的角色。我怎样才能实现它?可能与roleHierarchy.getReachableGrantedAuthorities但我不知道,该怎么把它作为参数。提前谢谢。

1 个答案:

答案 0 :(得分:4)

据我了解,您希望从给定的授权机构获得所有可达到的授权机构。如果是这种情况,以下是解决方案解决方案:

  • 首先从Spring RoleHierarchyImpl

    获取ApplicationContext实例
     ApplicationContext context = new FileSystemXmlApplicationContext(
            "--path--");
     BeanFactory factory = context;
     RoleHierarchyImpl roleHierarchy = (RoleHierarchyImpl) factory.getBean("roleHierarchy");`
    

或创建一个新实例并加载层次结构,如下所示;

     RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
     roleHierarchy.setHierarchy(properties.getProperty("security.roleHierarchy"));
  • 现在,您可以使用roleHierarchy.getReachableGrantedAuthoritiesAuthorityUtils获取所有可访问的授权机构:

     Collection<GrantedAuthority> ga = roleHierarchy.getReachableGrantedAuthorities(AuthorityUtils.createAuthorityList(new String[]{"ROLE_ADMIN"}));
    
相关问题