Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security Role Hierarchy not working with Thymeleaf sec:authorize

I'm using Spring Security 3.2.5.RELEASE with ThymeLeaf 2.1.4.RELEASE. I've defined Role Hierarchy in my security context. In my view layer I'm using sec:authorize attribute to define menu items. I expect to see all menu items under the top level role but I only see the menus defined under that role. How can I fix this problem so that I see all menus under the top level?

Any pointers would be really appreciated. Thanks.

<beans:bean id="roleVoter" class="org.springframework.security.access.vote.RoleHierarchyVoter">
    <beans:constructor-arg ref="roleHierarchy"/>
</beans:bean>

<beans:bean id="roleHierarchy" class="org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl">
    <beans:property name="hierarchy">
        <beans:value>
            ROLE_ADMINISTRATOR > ROLE_MANAGER > ROLE_CONTENT_ADMINISTRATOR
        </beans:value>
    </beans:property>
</beans:bean>

And in my view page I'm using sec:authorize attribute like below:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<body th:fragment="admin-menu" sec:authorize="hasRole('ROLE_ADMINISTRATOR')">
<li>
    <a href="#"><i class="fa fa-users"></i> <span class="nav-label">Users</span> </a>
</li>
</body>
</html>
like image 260
5dB Avatar asked Feb 19 '15 15:02

5dB


1 Answers

In order to get the role hierarchy worked in thymeleaf templates as well as in the common security (annotation) config, you need only 2 things:

  1. Make the bean:

    @Bean
    public RoleHierarchyImpl roleHierarchy() {
    RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
    String hierarchy =
            "ADMIN_GLOBAL_MANAGEMENT > ADMIN_COMMON " +
            "ADMIN_GLOBAL_MANAGEMENT > ADMIN_USER_MANAGEMENT " +
            "ADMIN_GLOBAL_MANAGEMENT > ADMIN_PAYMENT_MANAGEMENT " +
            "ADMIN_GLOBAL_MANAGEMENT > ADMIN_MESSAGE_MANAGEMENT";
     roleHierarchy.setHierarchy(hierarchy);
     return roleHierarchy;
    }
    
  2. Extend WebSecurityConfigurerAdapter and override a method:

    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    ...
    
    @Override
    public void configure(WebSecurity web) throws Exception {
      DefaultWebSecurityExpressionHandler expressionHandler = new 
        DefaultWebSecurityExpressionHandler();
      expressionHandler.setRoleHierarchy(roleHierarchy());
      web.expressionHandler(expressionHandler);
    }
    
like image 178
arctica Avatar answered Oct 27 '22 23:10

arctica