I am trying to secure my spring boot application with spring securitys own csrf library.
When I am sending requests to my backend authentication endpoint, the first request i send (without any cookies), gets 403 and my backend saying "Invalid CSRF token found for "http://localhost:8080/api/v1/auth/authenticate" That is sort of expected, since i didnt add the csrf token as a cookie. In the response, i also get additional headers:

Set-Cookie:
JSESSIONID=559A501CA3607510F67ACF0676C0ADF1; Path=/; HttpOnly
Set-Cookie:
XSRF-TOKEN=0b7c47cb-0c4e-4eca-9548-47e576c79759; Path=/

Now these cookies are added to my browser, so i would expect the next request to work, since spring handed me a new cookie which is, i assume, tied to the sessionid. My problem is, that i then again receive the same message: "Invalid CSRF token found for "http://localhost:8080/api/v1/auth/authenticate"

My SecurityConfig filter looks like this:

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private static final String[] WHITE_LIST_URL = {
            "/api/v1/auth/**",
            "/swagger-ui.html",
            "/swagger-ui/**",
            "/v3/api-docs/**",
            "/error",
            "/api/v1/demo-controller/demo"};
    private final JwtAuthenticationFilter jwtAuthFilter;
    private final AuthenticationProvider authenticationProvider;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf((csrf) -> csrf
                        .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
                )
                .authorizeHttpRequests(req ->
                        req.requestMatchers(WHITE_LIST_URL)
                                .permitAll()
                                .requestMatchers(HttpMethod.OPTIONS)
                                .permitAll()
                                .requestMatchers("/api/v1/admin/**").hasRole(ADMIN.name())
                                .anyRequest()
                                .authenticated()
                )
                .sessionManagement(session -> session.sessionCreationPolicy(ALWAYS))
                .authenticationProvider(authenticationProvider)
                .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }


}

I tried reading through spring documentation and implement their solution for single-page applications, pure javascript applications, and nothing seems to work.

Can someone help me on the right path here? 😀

Thanks in advance!

New contributor

slh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.