2
0

csrf.adoc 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. [[test-mockmvc-csrf]]
  2. = Testing with CSRF Protection
  3. When testing any non-safe HTTP methods and using Spring Security's CSRF protection, you must include a valid CSRF Token in the request.
  4. To specify a valid CSRF token as a request parameter use the CSRF xref:servlet/test/mockmvc/request-post-processors.adoc[`RequestPostProcessor`] like so:
  5. ====
  6. .Java
  7. [source,java,role="primary"]
  8. ----
  9. mvc
  10. .perform(post("/").with(csrf()))
  11. ----
  12. .Kotlin
  13. [source,kotlin,role="secondary"]
  14. ----
  15. mvc.post("/") {
  16. with(csrf())
  17. }
  18. ----
  19. ====
  20. If you like, you can include CSRF token in the header instead:
  21. ====
  22. .Java
  23. [source,java,role="primary"]
  24. ----
  25. mvc
  26. .perform(post("/").with(csrf().asHeader()))
  27. ----
  28. .Kotlin
  29. [source,kotlin,role="secondary"]
  30. ----
  31. mvc.post("/") {
  32. with(csrf().asHeader())
  33. }
  34. ----
  35. ====
  36. You can also test providing an invalid CSRF token by using the following:
  37. ====
  38. .Java
  39. [source,java,role="primary"]
  40. ----
  41. mvc
  42. .perform(post("/").with(csrf().useInvalidToken()))
  43. ----
  44. .Kotlin
  45. [source,kotlin,role="secondary"]
  46. ----
  47. mvc.post("/") {
  48. with(csrf().useInvalidToken())
  49. }
  50. ----
  51. ====