如何在springboot中禁用csrf检查集成测试

时间:2018-02-06 15:00:05

标签: spring spring-mvc spring-boot spring-security spring-boot-test

我想在为springboot应用程序进行集成测试时禁用csrf。我已经尝试过security.enable-csrf = false,但似乎没有任何效果。我也试过通过SecurityMockMvcRequestPostProcessors.csrf方法在我的测试中传递csrf令牌,但无济于事。

在我的应用程序中,有自定义SecurityConfig,它扩展了WebSecurityConfigurerAdapter,代码如下:

http
.csrf()                   .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.and()
.authorizeRequests()
.antMatchers(LOGIN_URL).permitAll()
.antMatchers("/api/v1/forgotpwd").permitAll()
.antMatchers("/api/v1/changepwd").permitAll()
.antMatchers("/api/v1/isLoggedIn").permitAll()
.antMatchers("/api/**").authenticated()
.and()
.logout().logoutUrl("/api/v1/logout").deleteCookies("JSESSIONID").invalidateHttpSession(true)
.logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler())
.and()
.addFilter(jsonUsernamePasswordAuthenticationFilter())
.addFilterAfter(new MDCEmailSetterFilter(),JsonUsernamePasswordAuthenticationFilter.class);

如果我设置http.csrf()。disable(),我的测试工作并且csrf令牌认证失败不会发生,否则会抛出403,消息说csrf令牌无法验证。

任何帮助?

1 个答案:

答案 0 :(得分:1)

http.csrf().disable()

您只能为测试配置文件调用它,例如

@Value("${spring.profiles.active}")
private String activeProfile;

if (activeProfile.trim().equalsIgnoreCase("integrational-tests")) {
    http.csrf().disable();
}
相关问题