首页 > Java > java教程 > 正文

Spring Boot API Key 认证测试指南

心靈之曲
发布: 2025-07-09 17:44:19
原创
669人浏览过

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 来实现。

假设我们有以下测试用例:

白瓜面试
白瓜面试

白瓜面试 - AI面试助手,辅助笔试面试神器

白瓜面试 40
查看详情 白瓜面试
@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 认证机制。这有助于确保端点的安全性,并验证其功能是否正常。记住,安全性测试是软件开发过程中不可或缺的一部分,应该贯穿整个开发周期。

以上就是Spring Boot API Key 认证测试指南的详细内容,更多请关注php中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号