使用 Spring Boot 3 禁用 Spring 的单元测试方法安全性

问题描述 投票:0回答:1

我在服务接口中的方法上使用

@PreAuthorize
。这些服务由
@RestController

使用

在 Spring Boot 2.x 中,我使用

@EnableGlobalMethodSecurity(prePostEnabled = true)

在自动配置中启用了方法安全性

在某些

@SpringBootTest
中,我们专注于测试功能逻辑,而不关心方法安全性。这些测试不会调用休息服务或控制器类。他们直接调用上面提到的服务类中的方法,这些服务类用
@PreAuthorize
注释。在这些测试中,我们通过

禁用了方法安全性
@EnableAspectJAutoProxy
class MyTestApplication extends MySringBootApplication {

    @Bean
    public GeFaJwtInterceptorTestAspect jwtInterceptorTestAspect() {
        return new GeFaJwtInterceptorTestAspect();
    }

    @Bean
    @Primary
    SecurityMetadataSource disableMethodSecurityForUnitTest() {
        return new DefaultFilterInvocationSecurityMetadataSource(Maps.newLinkedHashMap());
    }
}

效果很好。

迁移到 Spring Boot 3 后,我现在正在使用

@EnableMethodSecurity

如何在单元测试中禁用Spring的安全方法?

我阅读了文章https://docs.spring.io/spring-security/reference/servlet/authorization/method-security.html#enable-annotation但没有找到解决方案。

我试过了

  • @EnableMethodSecurity(prePostEnabled = false)
     使用 
    MyTestApplication
  • 在我的测试配置中添加一个 bean
      @Bean
      @Primary
      @Order(Ordered.HIGHEST_PRECEDENCE)
      AuthorizationManager<MethodInvocation> disableMethodSecurityForUnitTest1() {
          return (authentication, object) -> new AuthorizationDecision(true);
      }
    

但这没有用。每次尝试都会出现以下异常之一

org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext

org.springframework.security.access.AccessDeniedException: Access Denied

目前我唯一的解决办法是在每个测试方法上添加

@WithMockUser
,这不是我想要的,因为我只想测试功能逻辑。 (方法安全性也经过测试,但在我们应用程序的另一层上。)

java spring spring-boot spring-security
1个回答
0
投票

这就是我用来关闭本地运行或测试的安全性的方法。

  1. 默认禁用自动配置
@SpringBootApplication(exclude = { SecurityAutoConfiguration.class })
public class MyApplication {
// ...
}
  1. 使用配置文件(例如
    test
    )停用安全配置类
@Profile("!test")
@Configuration(proxyBeanMethods = false)
@EnableWebSecurity
@EnableMethodSecurity
public class WebSecurityConfig {
// ...
}
© www.soinside.com 2019 - 2024. All rights reserved.