我有一个像这样的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
之前尝试这样做时,我仍然会得到匿名用户。我试过这个:
template.withBasicAuth("User","pass");
它仍然不起作用。如何设置TestRestTemplate
安全上下文?
答案 0 :(得分:0)
我明白了。您需要创建一个实现WebSecurityConfigurerAdapter
的类,然后在那里设置上下文。这是你可以避免任何形式的嘲笑,我热衷于做这个更多的ETE集成测试。这是那个班级
public class TestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().permitAll().and().securityContext().securityContextRepository(new TestSecurityContextRepository());
}
}