集成测试中的 @PreAuthorize 导致 null beans

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

我正在开发一个与安全相关的 Spring Boot 入门库,以供其他应用程序使用。该库附带了类似于启动器的自动配置,一旦将该库添加为目标应用程序中的依赖项,该自动配置就会默认执行。它的作用是设置一个

filter
在处理 HTTP 请求之前运行,以便执行一些授权检查。

我想做的是在库中编写一个集成测试,“模拟”库逻辑在目标应用程序中运行时的行为。也就是说,向某个端点发送 HTTP 请求,并测试授权检查是否有效(或无效)。我的自动配置如下所示:

SecTestAutoconfiguration.kt

@AutoConfiguration @EnableMethodSecurity @ConditionalOnProperty( name = ["security.enabled"], havingValue = "true", matchIfMissing = true ) open class SecTestAutoconfiguration { // multiple @Bean definitions that don't matter }

现在在我的测试中,由于库中没有主类,因此我在 
src/test/kotlin/..

下创建一个主类。像这样:

测试应用程序.kt

@SpringBootApplication open class TestApplication

然后我的 IT 测试如下所示:

AppIT.kt

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureWebTestClient(timeout = "20000") class SecurityIT { @Autowired private lateinit var webTestClient: WebTestClient @Test fun test() { webTestClient.get() .uri("/test") .header(HttpHeaders.AUTHORIZATION, "some-token") .exchange() .expectStatus() .isOk() } }

最后我的测试控制器如下所示:

TestController.kt

@RestController open class TestController( ) { @Autowired private lateinit var applicationContext: ApplicationContext @GetMapping("/test") @PreAuthorize("hasRole('SOME_ROLE')") // This is problematic fun test() { println(applicationContext.id) } }

问题是,无论我在
TestController

中注入什么,似乎都是

null
。这似乎是由
@PreAuthorize
引起的,因为当我删除它时,
applicationContext
bean(或自动配置中定义的其他 bean)正在正确初始化。还尝试使用其他 spring-security 注释,如
@Secured
@RolesAllowed
但得到相同的结果,
null
beans。有什么想法吗?
    

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

我会尝试将 @PreAuthorize 移动到带有 @PreAuthorize 注释的测试方法的服务类中。这应该能够实现正确的注入,并且您可以进一步调试。

© www.soinside.com 2019 - 2024. All rights reserved.