Spring Boot + Spring Security + Hierarchical Roles

前端 未结 5 1816
甜味超标
甜味超标 2020-12-13 21:59

I\'m trying to setup hierarchical roles in my Spring Boot app without success. I\'ve done all that\'s been said in different places in the Internet. But with none of them ha

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-13 22:36

    I just went thru these setup so will definitely get you up running now. Here is the deal:

    You brought in this annotation @EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) but didn't show any code to use Pre/Post Authorize/Filter so I don't know if you actually need it.

    1. If you don't need that class/method level security/filtering then all you need to do is:

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

    and

            private SecurityExpressionHandler webExpressionHandler() {
                DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
                defaultWebSecurityExpressionHandler.setRoleHierarchy(roleHierarchy());
                return defaultWebSecurityExpressionHandler;
            }
    
    http
            .authorizeRequests()
            .expressionHandler(webExpressionHandler())
    

    You don't have to override with your own accessDecisionManager if all you need is to introduce a role hierarchy.

    1. If you also need class/method level security, i.e. using PreAuthorize, PostAuthorize, PreFilter, PostFilter on your methods/classes then also create a @Configuration like this in your classpath (and remove the @EnableGlobalMethodSecurity annotation from your GlobalMethodSecurityConfig class):

      @Configuration
      @EnableGlobalMethodSecurity(prePostEnabled=true)
      public class AnyNameYouLike extends GlobalMethodSecurityConfiguration {
      
      @Resource
      private RoleHierarchy roleHierarchy;
      
      @Override
      protected MethodSecurityExpressionHandler createExpressionHandler() {
          DefaultMethodSecurityExpressionHandler expressionHandler = (DefaultMethodSecurityExpressionHandler) super.createExpressionHandler();
          expressionHandler.setRoleHierarchy(roleHierarchy);
          return expressionHandler;
      }
      

      }

    I would give the name GlobalMethodSecurityConfig to this new class and change your current GlobalMethodSecurityConfig class to WebSecurityConfig or something to reflect that it's the security setting for the web tier.

    I define the RoleHierarchy bean in the webSecurityConfig and inject/use it in the globalMethodSecurityConfig, but you can do that any way you like, as long as you don't create 2 beans unnecessarily.

    Hope this helps.

提交回复
热议问题