CodexBloom - Programming Q&A Platform

Java 17 - Spring Security: CSRF Token Not Valid for REST API with Angular Client

👀 Views: 17 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-20
spring-security csrf angular Java

I'm sure I'm missing something obvious here, but I'm trying to implement I've encountered a strange issue with I've hit a wall trying to I've been banging my head against this for hours..... After trying multiple solutions online, I still can't figure this out. I'm working on a Spring Boot application that uses Spring Security for authentication and authorization. The backend is a REST API, and I'm trying to implement CSRF protection using Spring Security. However, I'm working with an scenario where the CSRF token seems to be invalid when making POST requests from my Angular client. After setting up CSRF protection, I configured my security settings as follows: ```java @Override protected void configure(HttpSecurity http) throws Exception { http .csrf() .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) .and() .authorizeRequests() .antMatchers(HttpMethod.POST, "/api/**").authenticated(); } ``` On the Angular side, I'm fetching the CSRF token and including it in the headers of my POST requests: ```javascript const csrfToken = this.getCookie('XSRF-TOKEN'); this.httpClient.post('/api/resource', data, { headers: { 'X-XSRF-TOKEN': csrfToken } }).subscribe(...); ``` However, I keep receiving a 403 Forbidden behavior with the message `Invalid CSRF token found for the session`. I've double-checked that the CSRF token is being sent in the request headers, and I can see that a new token is generated on the initial GET request. I've tried tweaking various configurations, such as enabling and disabling the `XSRF-TOKEN` cookie, and I've also verified that the token is not being cached in the browser. Additionally, I checked if other middleware might be interfering, but to no avail. Is there something I might be missing in the configuration or flow? Any insights on how to resolve this scenario would be greatly appreciated! I'm working on a API that needs to handle this. Am I missing something obvious? I'd really appreciate any guidance on this. Could this be a known issue? For reference, this is a production application. I'm open to any suggestions. Has anyone else encountered this?