Search code examples
javaspringspring-bootspring-mvc

How to disable CSRF in Spring Boot 3 only for tests


I'm writing tests for an application using Spring Boot 3.1.2. The application has csrf enabled, but the authorization in the tests fails when csrf is turned on, therefore I want to turn it off for the tests only.

My security config currently looks like this:

@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers(openUrls).permitAll()
            .anyRequest().hasAuthority(applicationRoleKey))
        .oauth2ResourceServer(oauth -> oauth
            .jwt(jwt -> jwt.jwtAuthenticationConverter(jwtAuthenticationConverter())));
    return http.build();
}

A sample test that is failing (get 406 instead of 400):

@Test
@WithMockUser(authorities = "user=admin")
void asAdmin_canGetPhoto() throws Exception {
  mockMvc.perform(MockMvcRequestBuilders.get("/photo")).andExpect(status().isOk());
}

What's the recommended way to disable CSRF only for tests? I can only find solutions using outdated versions of Spring Security.

Thanks for any guidance!

EDIT: Solved by adding .with(csrf()) to the tests.


Solution

  • It was solved by adding .with(csrf()) to the tests instead of disabling csrf for the tests:

    @Test
    @WithMockUser(authorities = "user=admin")
    void asAdmin_canGetPhoto() throws Exception {
      mockMvc.perform(
        MockMvcRequestBuilders.get("/photo")
          .with(csrf())
      ).andExpect(status().isOk());
    }
    

    As of Spring Security 6.4.2 the csrf() method is contained in the org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors class.