
本文档旨在指导开发者如何在 Spring Boot 应用程序中测试 API Key 认证。我们将通过一个实际案例,展示如何调整现有的集成测试,以便在请求中包含正确的 API Key,从而成功通过认证并验证端点的功能。
在 Spring Boot 应用中,API Key 认证是一种常见的安全机制,用于保护特定的端点。当需要对使用了 API Key 认证的端点进行测试时,我们需要确保测试用例能够正确地提供 API Key。以下将介绍如何通过修改测试代码,在请求头中添加 API Key,从而使测试通过认证。
假设我们有一个 Spring Boot 应用,其中 /validate 端点需要 API Key 认证。 认证逻辑通过自定义的 AuthFilter 实现,该过滤器会检查请求头中是否包含名为 API_KEY 的 Header,并验证其值是否与预定义的值匹配。
以下是一个简单的配置类示例:
@Configuration
@EnableWebSecurity
@Order(1)
public class AuthConfiguration {
public static final String API_KEY_VALUE = "skrdgvsnelrkv";
public static final String API_KEY_HEADER = "API_KEY";
@Value(API_KEY_HEADER)
private String principalRequestHeader;
@Value(API_KEY_VALUE)
private String principalRequestValue;
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
AuthFilter apiKeyFilter = new AuthFilter(principalRequestHeader);
apiKeyFilter.setAuthenticationManager(new AuthenticationManager() {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String principal = (String) authentication.getPrincipal();
if (!principalRequestValue.equals(principal)) {
throw new BadCredentialsException(
"The API key was not found or not the expected value."
);
}
authentication.setAuthenticated(true);
return authentication;
}
});
http.antMatcher(Endpoints.VALIDATE)
.csrf()
.disable()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.addFilter(apiKeyFilter)
.authorizeRequests()
.anyRequest()
.authenticated();
return http.build();
}
}在测试中,我们需要模拟客户端发送请求,并在请求头中包含正确的 API Key。这可以通过 MockMvc 来实现。
假设我们有以下测试用例:
@AutoConfigureTestEntityManager
@SpringBootTest
@ContextConfiguration(classes = { TestContext.class })
@TestPropertySource(properties = { "spring.main.allow-bean-definition-overriding=true" })
@AutoConfigureMockMvc
class ControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void callingValidateEndpointWithValidFileShouldReturnResponseWithStatusOk()
throws Exception {
MockMultipartFile file =
MockMultipathFileBuilder.buildFromFilePath(TestFiles.VALID_FILE);
mockMvc.perform(MockMvcRequestBuilders.multipart(Endpoints.VALIDATE).file(file))
.andExpect(status().isOk());
}
}由于缺少 API Key,该测试将会返回 403 Forbidden 错误。要解决这个问题,我们需要修改测试代码,在请求中添加 API Key Header。
修改后的测试代码如下所示:
@AutoConfigureTestEntityManager
@SpringBootTest
@ContextConfiguration(classes = { TestContext.class })
@TestPropertySource(properties = { "spring.main.allow-bean-definition-overriding=true" })
@AutoConfigureMockMvc
class ControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void callingValidateEndpointWithValidFileShouldReturnResponseWithStatusOk()
throws Exception {
MockMultipartFile file =
MockMultipathFileBuilder.buildFromFilePath(TestFiles.VALID_FILE);
mockMvc.perform(
MockMvcRequestBuilders.multipart(Endpoints.VALIDATE)
.file(file)
.header(AuthConfiguration.API_KEY_HEADER, AuthConfiguration.API_KEY_VALUE)
).andExpect(status().isOk());
}
}关键在于添加了 .header(AuthConfiguration.API_KEY_HEADER, AuthConfiguration.API_KEY_VALUE) 这部分代码。 它告诉 MockMvc 在请求头中添加 API_KEY Header,并将其值设置为 skrdgvsnelrkv。
通过在集成测试中添加 API Key Header,我们可以有效地测试 Spring Boot 应用中的 API Key 认证机制。这有助于确保端点的安全性,并验证其功能是否正常。记住,安全性测试是软件开发过程中不可或缺的一部分,应该贯穿整个开发周期。
以上就是Spring Boot API Key 认证测试指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号