For the latest stable version, please use Spring Security 6.4.0!

Testing with CSRF Protection

When testing any non-safe HTTP methods and using Spring Security’s CSRF protection, you must include a valid CSRF Token in the request. To specify a valid CSRF token as a request parameter use the CSRF RequestPostProcessor like so:

  • Java

  • Kotlin

mvc
	.perform(post("/").with(csrf()))
mvc.post("/") {
    with(csrf())
}

If you like, you can include CSRF token in the header instead:

  • Java

  • Kotlin

mvc
	.perform(post("/").with(csrf().asHeader()))
mvc.post("/") {
    with(csrf().asHeader())
}

You can also test providing an invalid CSRF token by using the following:

  • Java

  • Kotlin

mvc
	.perform(post("/").with(csrf().useInvalidToken()))
mvc.post("/") {
    with(csrf().useInvalidToken())
}