Spring Security Role Hierarchy not working using Java Config

前端 未结 6 2119
轻奢々
轻奢々 2021-01-04 21:48

First of all, I am new to Java Spring Framework. So forgive me if I did not provide enough info. I have tried to add RoleHierarchy into my app but it did not work. Below are

6条回答
  •  Happy的楠姐
    2021-01-04 21:53

    Everytime I want to implement a hierarchy of roles with Spring Security and Java config, I use the following approach:

    1. We have to add a RoleHierarchyImpl bean into context (You see, that I use multiple roles to build a hierarchy):

      @Bean
      public RoleHierarchyImpl roleHierarchy() {
          RoleHierarchyImpl roleHierarchy = new RoleHierarchyImpl();
          roleHierarchy.setHierarchy("ROLE_ADMIN > ROLE_DBA ROLE_DBA > ROLE_USER ");
          return roleHierarchy;
      }
      
    2. Then we need to create web expression handler to pass obtained hierarchy to it:

      private SecurityExpressionHandler webExpressionHandler() {
          DefaultWebSecurityExpressionHandler defaultWebSecurityExpressionHandler = new DefaultWebSecurityExpressionHandler();
          defaultWebSecurityExpressionHandler.setRoleHierarchy(roleHierarchy());
          return defaultWebSecurityExpressionHandler;
      }
      
    3. The final step is to add expressionHandler into http.authorizeRequests():

              @Override
              protected void configure(HttpSecurity http) throws Exception {
                  http
                     .authorizeRequests()
                          .expressionHandler(webExpressionHandler())
                          .antMatchers("/admin/**").access("(hasRole('ROLE_ADMIN') or hasRole('ROLE_DBA')) and isFullyAuthenticated()")
                          .antMatchers("/dba").access("hasRole('ROLE_DBA') and isFullyAuthenticated()")
                          .antMatchers("/dba/**").access("hasRole('ROLE_USER')")
                          .and()
                     .requiresChannel()
                          .antMatchers("/security/**").requiresSecure()
                          .anyRequest().requiresInsecure()
                          .and()
                     .formLogin()
                          .loginPage("/login")
                          .failureUrl("/login?auth=fail")
                          .usernameParameter("username")
                          .passwordParameter("password")
                          .defaultSuccessUrl("/admin")
                          .permitAll()
                          .and()
                     .logout()
                              .logoutUrl("/logout")
                              .deleteCookies("remember-me")
                              .invalidateHttpSession(true)
                              .logoutSuccessUrl("/index")
                              .permitAll()
                              .and()
                     .csrf()
                              .and()
                     .rememberMe().tokenValiditySeconds(1209600)
                              .and()
                     .exceptionHandling().accessDeniedPage("/403")
                              .and()
                     .anonymous().disable()
                     .addFilter(switchUserFilter());
              }
      

    Result: in this particular example we try to visit /dba section after we have logged in using admin user (ROLE_ADMIN). Before we created a hierarchy, we had an access denied result, but now we can visit this section without any problems.

提交回复
热议问题