使用CSRF保护进行测试
当测试任何非安全HTTP方法并使用Spring Security的CSRF保护时,您必须在请求中包含有效的CSRF令牌。要将有效的CSRF令牌指定为请求参数,请使用CSRF RequestPostProcessor,如下所示
-
Java
-
Kotlin
mvc
.perform(post("/").with(csrf()))
mvc.post("/") {
with(csrf())
}
如果您愿意,可以改为在请求头中包含CSRF令牌
-
Java
-
Kotlin
mvc
.perform(post("/").with(csrf().asHeader()))
mvc.post("/") {
with(csrf().asHeader())
}
您还可以通过使用以下方式测试提供无效的CSRF令牌
-
Java
-
Kotlin
mvc
.perform(post("/").with(csrf().useInvalidToken()))
mvc.post("/") {
with(csrf().useInvalidToken())
}