【问题标题】:How to disable csrf checks for integration tests in springboot如何在spring boot中禁用csrf检查以进行集成测试
【发布时间】:2018-07-16 16:31:42
【问题描述】:

我想在为我的 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 令牌的消息。

有什么帮助吗?

【问题讨论】:

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


    【解决方案1】:
    http.csrf().disable()
    

    您只能将其用于测试配置文件,例如

    @Value("${spring.profiles.active}")
    private String activeProfile;
    
    if (activeProfile.trim().equalsIgnoreCase("integrational-tests")) {
        http.csrf().disable();
    }
    

    【讨论】:

    • 是的,这可行,但有点侵入性。我不知道为什么 SecurityMockMvcRequestPostProcessors.csrf 方法调用不起作用?
    【解决方案2】:

    我能够测试我的@WebMvcTest,这样做:

    静态导入 SecurityMockMvcRequestPostProcessors.*:

    import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*;
    

    然后在你的 mockMvc 请求中,你可以使用:

    with(csrf())
    

    最后,你的请求会是这样的:

            this.mockMvc
                .perform(post("/users").with(csrf())
                        .content(objectMapper.writeValueAsString(createUserDto))
                        .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE))
                .andExpect(status().isCreated());
    

    Spring 文档的完整解释可以在

    找到

    如第二个链接所述

    什么时候应该使用 CSRF 保护?我们的建议是对普通用户可以通过浏览器处理的任何请求使用 CSRF 保护。如果您只创建非浏览器客户端使用的服务,您可能需要禁用 CSRF 保护。

    【讨论】:

      猜你喜欢
      • 2018-05-04
      • 1970-01-01
      • 2018-02-01
      • 2020-07-24
      • 2019-12-23
      • 2019-08-17
      • 1970-01-01
      • 2014-08-15
      • 2020-04-09
      相关资源
      最近更新 更多