Spring boot security 6 - swagger 3: CSRF token only worked second call

101 Views Asked by At

I'm implementing spring boot security in our Java 17 project which uses Swagger 3. The login procedure appears when navigating to the swagger-UI before we can call one the endpoints. Which is normal. The login is successful and I'm navigated to the API-endpoints overview. So far so good.

When I want to execute one of the endpoints, the login message appears again and spring security logs says 'invalid CSRF token'. When I cancel the login pop-up and refresh the page. The login pop-up appears again. After successful login I'm again redirected to the API-endpoints overview. If I execute one of the API-endpoints again the call is successful and so the CSRF-token is valid.

Has anyone an idea why this flow occurs?

The security configuration class looks like below

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                /*
                 * Support Javascript based applications (use json instead of HTML)
                 * Otherwise application throws 'Invalid CSRF token'
                 * https://docs.spring.io/spring-security/reference/6.1-SNAPSHOT/servlet/exploits/csrf.html
                */
                .csrf((csrf) -> csrf
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                        .csrfTokenRequestHandler(new CsrfTokenRequestAttributeHandler())
                )
                .authorizeHttpRequests(requests -> requests
                        .anyRequest().authenticated()
                )
                .httpBasic(Customizer.withDefaults());

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

I enabled CSRF token in swagger 3 by setting the property below in application.yml

springdoc:
  swagger-ui:
    csrf:
      enabled: true

Kind regards

Successfully call API-endpoints via Swagger 3 at the first attempt after the login procedure.

0

There are 0 best solutions below