测试期间弹簧丢失安全上下文

时间:2017-06-21 20:28:34

标签: java spring rest spring-security

我有一个像这样的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();

以下是上下文的内容: enter image description here

我需要设置安全上下文,以便它不是匿名的。我可以这样做:

SecurityContext context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authResult);
SecurityContextHolder.setContext(context);

但是当我在template.exchange之前尝试这样做时,我仍然会得到匿名用户。我试过这个:

template.withBasicAuth("User","pass");

它仍然不起作用。如何设置TestRestTemplate安全上下文?

1 个答案:

答案 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());
    }
}
相关问题