Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class CsrfDsl {
private var ignoringRequestMatchers: Array<out RequestMatcher>? = null
private var ignoringRequestMatchersPatterns: Array<out String>? = null
private var disabled = false
private var spaMode = false

/**
* Allows specifying [HttpServletRequest]s that should not use CSRF Protection
Expand Down Expand Up @@ -76,6 +77,17 @@ class CsrfDsl {
disabled = true
}

/**
* Sensible CSRF defaults when used in combination with a single page application.
* Creates a cookie-based token repository and a custom request handler to resolve the
* actual token value instead of the encoded token.
*
* @since 7.1
*/
fun spa() {
spaMode = true
}

internal fun get(): (CsrfConfigurer<HttpSecurity>) -> Unit {
return { csrf ->
csrfTokenRepository?.also { csrf.csrfTokenRepository(csrfTokenRepository) }
Expand All @@ -84,6 +96,9 @@ class CsrfDsl {
csrfTokenRequestHandler?.also { csrf.csrfTokenRequestHandler(csrfTokenRequestHandler) }
ignoringRequestMatchers?.also { csrf.ignoringRequestMatchers(*ignoringRequestMatchers!!) }
ignoringRequestMatchersPatterns?.also { csrf.ignoringRequestMatchers(*ignoringRequestMatchersPatterns!!) }
if (spaMode) {
csrf.spa()
}
if (disabled) {
csrf.disable()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -343,4 +343,40 @@ class CsrfDslTests {
return http.build()
}
}

@Test
fun `POST when CSRF for SPA enabled and no CSRF token then forbidden`() {
this.spring.register(CsrfSPAConfig::class.java).autowire()

this.mockMvc.post("/test1")
.andExpect {
status { isForbidden() }
}
}

@Test
fun `POST when CSRF for SPA enabled and CSRF token then status OK`() {
this.spring.register(CsrfSPAConfig::class.java, BasicController::class.java).autowire()

this.mockMvc.post("/test1") {
with(csrf())
}.andExpect {
status { isOk() }
}

}

@Configuration
@EnableWebSecurity
open class CsrfSPAConfig {
@Bean
open fun securityFilterChain(http: HttpSecurity): SecurityFilterChain {
http {
csrf {
spa()
}
}
return http.build()
}
}
}
Loading