matejuh
matejuh

Reputation: 406

How to get all roles from RoleHierarchyImpl

I have a hierarchy of roles configured and working:

<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>

For user roles setting I need to access which roles I have defined. How can I achieve it? Probably with roleHierarchy.getReachableGrantedAuthorities but I dont know, what to give it as parameter. Thanks in advance.

Upvotes: 2

Views: 1913

Answers (1)

Alpesh Tarapara
Alpesh Tarapara

Reputation: 61

As I understand, you want to get all the reachable granted authorities from a given granted authority. If this is the case, below is the workaround solution:

  • First get the RoleHierarchyImpl instance either from Spring ApplicationContext

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

or create a new instance and load the Hierarchy as like below;

     RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
     roleHierarchy.setHierarchy(properties.getProperty("security.roleHierarchy"));
  • Now you can use roleHierarchy.getReachableGrantedAuthorities and AuthorityUtils to get all the reachable granted authorities:

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

Upvotes: 6

Related Questions