0
時のセキュリティコンテキストを失う:春私はこのような春のブート統合テストを持ってテスト
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles("Test")
@RunWith(SpringRunner.class)
public class HelloControllerIT {
@Autowired
protected TestRestTemplate template;
@Test
public void test1() throws Exception {
HttpEntity request = //buildJson;
ResponseEntity response = template.exchange("/put", HttpMethod.PUT, request, Object.class);
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED);
}
}
テンプレートは、要求を送信すると、次のようになります私のコード内のポイントがあります:
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
は、
匿名でないようにセキュリティコンテキストを設定する必要があります。私はこのようにそれを行うことができます。
SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authResult);
SecurityContextHolder.setContext(context);
しかし、私はtemplate.exchange
前に、私はまだanonymousUserを得ることをやるしようとします。私はこれを試してみました:
template.withBasicAuth("User","pass");
それでも動作しません。 TestRestTemplate
セキュリティコンテキストを設定するにはどうすればよいですか?
おそらく '@ EnableWebSecurity'と' @ WithMockUser'アノテーションが必要です。 – ngreen