升级到Spring Security 6后角色层次结构不工作

v2g6jxz6  于 2023-01-01  发布在  Spring
关注(0)|答案(1)|浏览(296)

我正在从Sping Boot 2. 7. x升级到3. 0. 0。在按照官方文档中的建议做了更改后,我发现我的角色层次结构没有得到尊重。
我按照AccessDecisionVoter Deprecated with Spring Security 6.x中的建议将expressionHandler()添加到代码中,但它不起作用。
你知道我漏掉了什么吗?

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

  @Bean
  public SecurityFilterChain configure(
      HttpSecurity http,
      RequestHeaderAuthenticationFilter headerAuthenticationFilter) throws Exception {
    
    HttpStatusEntryPoint authenticationEntryPoint = 
        new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
    
    http
        .addFilterAfter(headerAuthenticationFilter, RequestHeaderAuthenticationFilter.class)
        .authorizeHttpRequests(auth -> auth
          .requestMatchers("/actuator/**", "/", "/webjars/**").permitAll()
          .requestMatchers(HttpMethod.POST).hasRole("SUPERUSER")
          .requestMatchers(HttpMethod.GET).hasRole("USER"))
        .sessionManagement(session -> session
          .sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .exceptionHandling(ex -> ex
          .authenticationEntryPoint(authenticationEntryPoint)
          .accessDeniedHandler(accessDeniedHandler()))
        .csrf(customizer -> customizer.disable());

    return http.build();
  }

  @Bean
  public RequestHeaderAuthenticationFilter headerAuthenticationFilter(
      ...
  }

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

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

oaxa6hgo1#

AuthorityAuthorizationManager没有作为bean公开。实际上,它是一个带有私有构造函数的final类。因此,为了使用我的角色层次结构,我需要手动创建AuthorityAuthorizationManager。
这在使用 Spring Boot 3.0.0和 spring security 6.0.0时有效

@Bean
  public SecurityFilterChain configure(
      HttpSecurity http,
      RequestHeaderAuthenticationFilter headerAuthenticationFilter) throws Exception {

    var auth1 = AuthorityAuthorizationManager.<RequestAuthorizationContext>hasRole("USER");
    auth1.setRoleHierarchy(roleHierarchy());
    
    http
        .authorizeHttpRequests(auth -> auth
          .requestMatchers(HttpMethod.GET).access(auth1)
        );
    return http.build();
  }

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

相关问题