在标注了 @SpringBootTest的测试中如何禁用安全性?
我正在尝试理解Spring Security,在实现集成测试时遇到困难。
我在使用Spring Boot 4.0.3,带有 spring-boot-starter-webmvc、spring-boot-starter-webmvc-test、spring-boot-starter-security、spring-boot-starter-security-test 这些依赖。
下面是一个REST控制器。
@RestController
public class DemoController {
@GetMapping("/unsecured/home")
public String unsecuredHome(HttpServletRequest request) {
return request.getRequestURI()
.toUpperCase();
}
}
下面是测试类。
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class DemoControllerIntegrationTest {
@LocalServerPort
private int port;
private RestTestClient restClient;
@BeforeEach
void beforeEachTest() {
restClient = RestTestClient.bindToServer()
.baseUrl("http://localhost:" + port)
.build();
}
@Test
void should_return_uppercase_request_uri_unsecured_home() {
String uri = "/unsecured/home";
String expected = "/UNSECURED/HOME";
restClient.get()
.uri(uri)
.exchange()
.expectStatus()
.isOk()
.expectBody(String.class)
.isEqualTo(expected);
}
}
测试失败,错误信息如下
java.lang.AssertionError: Status expected:<200 OK> but was:<401 UNAUTHORIZED>
Expected :200 OK
Actual :401 UNAUTHORIZED
这是我想知道的:
- 使用
RestTestClient.bindToServer()时,在集成测试中如何忽略/跳过/禁用安全性? - 使用
RestTestClient.bindToServer()时,在集成测试中实现安全性的正确方式是什么?
目前我不想定义一个单独的Spring配置文件(profile),也不想在该配置文件上定义安全过滤链并用该配置文件来运行测试。
- 我尝试在application.properties文件中添加
spring.autoconfigure.exclude = org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration,但不起作用。 - 我尝试在测试类中使用
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class),但不起作用。 - 我尝试在测试类中使用
@AutoConfigureMockMvc(addFilters = false),但不起作用。 - 我在测试方法上尝试了
@WithMockUser和@WithAnonymousUser,但都不起作用。*
解决方案
针对配置 RestTestClient 的第一个问题的解答:是的,这是一个有效的方法。你甚至可以通过以下方式节省一些敲击次数:
@AutoConfigureRestTestClient
然后Spring Boot将为你的应用自动配置客户端,并将其绑定到正确的随机端口。
要完全禁用Spring Boot集成测试中的安全性,你可以这样做:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
properties = "spring.autoconfigure.exclude=" +
"org.springframework.boot.security.autoconfigure.SecurityAutoConfiguration," +
"org.springframework.boot.security.autoconfigure.web.servlet.SecurityFilterAutoConfiguration," +
"org.springframework.boot.security.autoconfigure.UserDetailsServiceAutoConfiguration," +
"org.springframework.boot.security.autoconfigure.web.servlet.ServletWebSecurityAutoConfiguration"
)
作为替代,你也可以定义一个测试用的安全配置,简单地允许所有请求:
@TestConfiguration
static class NoSecurityConfig {
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
SecurityFilterChain permitAll(HttpSecurity http) throws Exception {
return http
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
.csrf(csrf -> csrf.disable())
.build();
}
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。