quma
quma

Reputation: 5753

Spring (Boot) application and csrf

I use this statements in the WebSecurityConfigurerAdapter#configure method to secure my application. If csrf is disabled (http.csrf().disable();) than everything works fine, if I remove this line than I get an exception (Forbidden 403). It is not clear for me why - I want to be safe against csrf- attack. Does anyone know what I am doing wrong?

@Override
protected void configure(final HttpSecurity http) throws Exception {

    final List<String> activeProfiles = Arrays.asList(environment.getActiveProfiles());

    final CsrfTokenResponseHeaderBindingFilter csrfFilter = csrfTokenResponseHeaderBindingFilter();
    http.addFilterAfter(csrfFilter, CsrfFilter.class).headers().cacheControl().xssProtection();

    http.csrf().disable();
    http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

    final String[] restEndpointsToSecure = WebSecurityConfig.restEndpointsToSecure;
    for (final String endpoint : restEndpointsToSecure) {
        http.authorizeRequests().antMatchers("/" + endpoint + "/**").hasRole(UserRoleEnum.USER.toString());
    }
    xAuthTokenConfigurer.setDetailsService(userDetailsServiceBean());
    final SecurityConfigurer<DefaultSecurityFilterChain, HttpSecurity> securityConfigurerAdapter = xAuthTokenConfigurer;
    http.apply(securityConfigurerAdapter);
}

Upvotes: 0

Views: 412

Answers (1)

Kyle Anderson
Kyle Anderson

Reputation: 7051

Spring Security CSRF Documentation

You need to include the token in your requests. If you use Thymeleaf as your templating engine, this is handled automatically. The documentation also describes how to handle Ajax as well.

Upvotes: 1

Related Questions