Alberto Costa
Alberto Costa

Reputation: 137

Spring Security: method to check if a user has a Hierarchical Role

how i can check if a user has a hierarchical role at runtime ? I know this solution for the url authorization @PreAuthorize("hasRole('ROLE_ADMIN')") but inside a method if i have to check the role ?

For example:

ROLE_ADMIN > ROLE_USER > ROLE_GUEST

if (user.hasRole('ROLE_USER')){
    do something;
}

In this example the condition must to be true if the user has the ROLE_ADMIN because in hierarchical roles ROLE_ADMIN > ROLE_USER.

Thanks

Upvotes: 3

Views: 2554

Answers (1)

Alberto Costa
Alberto Costa

Reputation: 137

Thanks all for your replies. Maybe i found a solution. I created a custom hierarchical role system with this @Configuration:

    @Bean
    public RoleHierarchy roleHierarchy(){
        RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
        roleHierarchy.setHierarchy("ROLE_SUPERADMIN > ROLE_ADMIN ROLE_ADMIN > ROLE_USER ROLE_USER > ROLE_GUEST");
        return roleHierarchy;
    }

    @Bean
    public RoleHierarchyVoter roleVoter() {     
        return new RoleHierarchyVoter(roleHierarchy());
    }

    @Bean 
    public DefaultWebSecurityExpressionHandler expressionHandler(){
        DefaultWebSecurityExpressionHandler expressionHandler = new DefaultWebSecurityExpressionHandler();
        expressionHandler.setRoleHierarchy(roleHierarchy());
        return expressionHandler;
    }

After that i created an help function:

public static boolean hasHierarchyRole(String role, RoleHierarchy roleHierarchy) {

        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();

        Collection<? extends GrantedAuthority> hierarchyAuthorities = roleHierarchy.getReachableGrantedAuthorities(authorities);

        for (GrantedAuthority authority : hierarchyAuthorities) {
            if (authority.getAuthority().equals(role)) {
                return true;
            }
        }

        return false;
    }

and seems to work.

Upvotes: 3

Related Questions