Spring Boot API Key 认证测试指南

Spring Boot API Key 认证测试指南

本文档旨在指导开发者如何在 spring Boot 应用程序中测试 API Key 认证。我们将通过一个实际案例,展示如何调整现有的集成测试,以便在请求中包含正确的 API Key,从而成功通过认证并验证端点的功能。

spring boot 应用中,API Key 认证是一种常见的安全机制,用于保护特定的端点。当需要对使用了 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。

注意事项

  • 确保 AuthConfiguration.API_KEY_HEADER 和 AuthConfiguration.API_KEY_VALUE 的值与实际应用中的配置一致。
  • 在实际项目中,API Key 应该以安全的方式存储和管理,避免硬编码在代码中。可以使用环境变量、配置文件或专门的密钥管理服务。
  • 在编写测试用例时,应尽可能覆盖各种场景,例如:
    • API Key 缺失
    • API Key 值不正确
    • API Key 值正确

总结

通过在集成测试中添加 API Key Header,我们可以有效地测试 Spring Boot 应用中的 API Key 认证机制。这有助于确保端点的安全性,并验证其功能是否正常。记住,安全性测试是软件开发过程中不可或缺的一部分,应该贯穿整个开发周期。

© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享