【问题标题】:Spring Losing Security Context during TestingSpring 在测试期间丢失安全上下文
【发布时间】: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


【解决方案1】:

我想通了。您需要创建一个实现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());
    }
}

【讨论】:

  • TestSecurityContextRepository 在哪里?我只找到了一个我无法使用的私人课程。
猜你喜欢
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2013-08-18
  • 1970-01-01
  • 2015-09-13
  • 1970-01-01
  • 2012-09-30
  • 2012-08-01
相关资源
最近更新 更多