servlet-test-mockmvc-csrf.md 893 字节
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
# Testing with CSRF Protection

When testing any non-safe HTTP methods and using Spring Security’s CSRF protection, you must be sure to include a valid CSRF Token in the request.
To specify a valid CSRF token as a request parameter use the CSRF [`RequestPostProcessor`](request-post-processors.html) like so:

Java

```
mvc
	.perform(post("/").with(csrf()))
```

Kotlin

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

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

Java

```
mvc
	.perform(post("/").with(csrf().asHeader()))
```

Kotlin

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

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

Java

```
mvc
	.perform(post("/").with(csrf().useInvalidToken()))
```

Kotlin

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

[Mocking Users](authentication.html)[Mocking Form Login](form-login.html)