csrf.adoc 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 be sure to 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. [tabs]
  6. ======
  7. Java::
  8. +
  9. [source,java,role="primary"]
  10. ----
  11. mvc
  12. .perform(post("/").with(csrf()))
  13. ----
  14. Kotlin::
  15. +
  16. [source,kotlin,role="secondary"]
  17. ----
  18. mvc.post("/") {
  19. with(csrf())
  20. }
  21. ----
  22. ======
  23. If you like you can include CSRF token in the header instead:
  24. [tabs]
  25. ======
  26. Java::
  27. +
  28. [source,java,role="primary"]
  29. ----
  30. mvc
  31. .perform(post("/").with(csrf().asHeader()))
  32. ----
  33. Kotlin::
  34. +
  35. [source,kotlin,role="secondary"]
  36. ----
  37. mvc.post("/") {
  38. with(csrf().asHeader())
  39. }
  40. ----
  41. ======
  42. You can also test providing an invalid CSRF token using the following:
  43. [tabs]
  44. ======
  45. Java::
  46. +
  47. [source,java,role="primary"]
  48. ----
  49. mvc
  50. .perform(post("/").with(csrf().useInvalidToken()))
  51. ----
  52. Kotlin::
  53. +
  54. [source,kotlin,role="secondary"]
  55. ----
  56. mvc.post("/") {
  57. with(csrf().useInvalidToken())
  58. }
  59. ----
  60. ======