Я использую Spring org.springframework.boot.test.web.client.TestRestTemplate
для тестирования кода контроллера.
Я могу протестировать API GET, просто используя testRestTemplate.withBasicAuth("test", "test").exchange(...)
, но тот же способ не работает для конечных точек POST в том же контроллере.
Он возвращает HttpStatus 302 found
со следующим ResponseEntity:
<302,[Set-Cookie:"JSESSIONID=332C559B7CABE5682EE9910A6FF834DA; Path=/; HttpOnly", X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY", Location:"http://localhost:61598/login", Content-Length:"0", Date:"Thu, 09 Jul 2020 14:24:18 GMT", Server:"Application Server"]>
Код контроллера:
@GetMapping(value = "/filterable_columns", produces = "application/json")
public List<FilterableField> filterableFieldList() {
log.info("Received request for list of filterable fields");
return metaDataService.filterableFieldList(referenceDataService.getSchemaUri());
}
@PostMapping(value = "/search", produces = "application/json")
public List<Map<String, Object>> filteredSearch(@RequestBody FilteredSearchRequest filteredSearchRequest) throws IllegalAccessException {
log.info("Received request for filtered search");
return referenceDataService.filteredSearch(filteredSearchRequest);
}
Тест контроллера:
@Test // This works as expected
void filterableFieldList() {
val reply = testRestTemplate.withBasicAuth("test", "test")
.exchange("/reference_data/filterable_columns",
HttpMethod.GET, null,
new ParameterizedTypeReference<List<FilterableField>>() {
});
assertEquals(HttpStatus.OK, reply.getStatusCode());
assertFalse(Objects.requireNonNull(reply.getBody()).isEmpty());
}
@Test // This does not work
void filteredSearch() {
val reply = testRestTemplate.withBasicAuth("test", "test")
.exchange("/reference_data/search",
HttpMethod.POST,
new HttpEntity<>(new FilteredSearchRequest()),
new ParameterizedTypeReference<List<Map<String, Object>>>() {
}
);
System.out.println(reply);
assertEquals(HttpStatus.OK, reply.getStatusCode());
}
AdfsSecurityConfiguration. java:
@Configuration
@ConditionalOnProperty(prefix = "moneta.security.adfs", name = "enabled", matchIfMissing = true)
public class AdfsSecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Environment environment;
private final AdfsConfigurer<HttpSecurity> adfsConfigurer;
public AdfsSecurityConfiguration(final Environment environment, final AdfsConfigurer<HttpSecurity> adfsConfigurer) {
this.environment = environment;
this.adfsConfigurer = adfsConfigurer;
}
@Override
protected void configure(final HttpSecurity http) throws Exception {
if (!isRunningLocally()) {
http.requiresChannel().anyRequest().requiresSecure();
}
http.apply(adfsConfigurer).and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().authorizeRequests()
.requestMatchers(EndpointRequest.to("keepalive", "info", "health", "env"), EndpointRequest.toLinks())
.permitAll().anyRequest().authenticated().and().csrf().disable();
}
private boolean isRunningLocally() {
return environment.acceptsProfiles(Profiles.of("default"));
}
}
application-test.yml:
spring:
security:
user:
name: test
password: test