springspring-mvcspring-securityspring5

how to write a test to make sure CSRF is not disabled


JAVA 8 + SPRING 5 + Junit - no Spring boot

I have sample following spring configuration. I want to write a basic test to test the configuration if some one turns csrf configuration off test should fail.

by default csrf is enable that's why you won't see any csrf configuration.

any help is appreciated in advance.

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
public class WebMVCSecurity extends WebSecurityConfigurerAdapter {

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
          .withUser("user1").password("{noop}user1Pass")
          .authorities("ROLE_USER");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/resources/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
          .anyRequest()
          .authenticated()
          .and()
          .httpBasic();
    }
}

Solution

  • all the spring security configuration ultimately converts into FilterChainProxy object with you can auto wire and then iterate over filters look for CsrfFilter class if csrf is enable.