在Sping Boot 中测试API密钥身份验证

iecba09b  于 2022-11-05  发布在  Spring
关注(0)|答案(1)|浏览(197)

我有一个Sping Boot 应用程序,其中的端点使用如下所示的API密钥进行保护:

@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();
    }
}

我以前测试过这个端点,但是现在他们失败了,出现了一个403禁止的错误,这是可以理解的。

@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());
    }
}

我需要如何调整此测试才能通过?

wmomyfyw

wmomyfyw1#

所需要做的就是将API密钥添加为头文件,如下所示:.header(AuthConfiguration.API_KEY_HEADER, AuthConfiguration.API_KEY_VALUE)
这意味着测试应该如下所示:

@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());
    }

相关问题