Create CsrfCustomizer for SPA configuration

Closes gh-14149

Signed-off-by: Felix Hagemans <felixhagemans@gmail.com>
This commit is contained in:
Felix Hagemans
2025-04-18 14:18:24 +02:00
committed by Josh Cummings
parent 52394c1f07
commit 1a4de49977
3 changed files with 109 additions and 91 deletions

View File

@@ -93,6 +93,7 @@ import static org.springframework.test.web.servlet.request.MockMvcRequestBuilder
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.request;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.cookie;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.redirectedUrl;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@@ -613,6 +614,37 @@ public class CsrfConfigurerTests {
assertThat(cookies).isEmpty();
}
@Test
public void spaConfigForbidden() throws Exception {
this.spring.register(CsrfSpaConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(post("/")).andExpect(status().isForbidden());
}
@Test
public void spaConfigOk() throws Exception {
this.spring.register(CsrfSpaConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
this.mvc.perform(post("/").with(csrf())).andExpect(status().isOk());
}
@Test
public void spaConfigDoubleSubmit() throws Exception {
this.spring.register(CsrfSpaConfig.class, AllowHttpMethodsFirewallConfig.class, BasicController.class)
.autowire();
var token = this.mvc.perform(post("/"))
.andExpect(status().isForbidden())
.andExpect(cookie().exists("XSRF-TOKEN"))
.andReturn()
.getResponse()
.getCookie("XSRF-TOKEN");
this.mvc
.perform(post("/").header("X-XSRF-TOKEN", token.getValue())
.cookie(new Cookie("XSRF-TOKEN", token.getValue())))
.andExpect(status().isOk());
}
@Configuration
static class AllowHttpMethodsFirewallConfig {
@@ -1006,6 +1038,18 @@ public class CsrfConfigurerTests {
}
@Configuration
@EnableWebSecurity
static class CsrfSpaConfig {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(CsrfConfigurer::spa);
return http.build();
}
}
@Configuration
@EnableWebSecurity
static class HttpBasicCsrfTokenRequestHandlerConfig {