【发布时间】:2017-11-24 22:12:19
【问题描述】:
我有一个这样的 Spring Boot 集成测试:
@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注释。
标签: java spring rest spring-security