Java 使用Spock使用Spring Security测试Spring引导应用程序
我正在尝试使用SpringSecurity对SpringBoot应用程序进行集成测试Java 使用Spock使用Spring Security测试Spring引导应用程序,java,spring,spring-mvc,spring-security,spock,Java,Spring,Spring Mvc,Spring Security,Spock,我正在尝试使用SpringSecurity对SpringBoot应用程序进行集成测试 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class ApplicationSpec extends Specification{ @Autowired TestRestTemplate testRestTemplate def setup() { Basic
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class ApplicationSpec extends Specification{
@Autowired
TestRestTemplate testRestTemplate
def setup() {
BasicAuthorizationInterceptor bai = new BasicAuthorizationInterceptor("username", "password")
testRestTemplate.getRestTemplate().getInterceptors().add(bai)
}
所有依赖项都在那里,testrestemplate被注入。问题是当我尝试测试POST端点时。我发现以下错误:
无法验证提供的CSRF令牌,因为您的会话不可用
找到了
如何获取有效的CSRF令牌并将其提供给我的TestRestTemplate?您可以在WebSecurity配置适配器中禁用CSRF。我不想这样做。您应该首先调用get并提取CSRF令牌
response.headers['x-CSRF-token']
,然后在标头中使用令牌发送。