spring testRestTemplate基本身份验证不适用于POST请求Httpstatus 302

时间:2020-07-09 14:41:45

标签: spring spring-boot junit spring-security spring-test

我正在使用Spring的org.springframework.boot.test.web.client.TestRestTemplate测试控制器代码。

我可以简单地使用testRestTemplate.withBasicAuth("test", "test").exchange(...)来测试GET API,但是对于同一控制器中的POST端点而言,相同的方法不起作用。

它返回带有以下ResponseEntity的HttpStatus 302 found

<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

0 个答案:

没有答案