I'm having problems with test controllers that use Play CSRF protection. To demonstrate this, I created a very simple Play application that minimally demonstrates the problem.
https://github.com/adamnfish/csrftest
Full details are contained in the README of this repository, but in brief:
Consider a controller designed to handle form submissions. It has a GET method that uses CSRFAddToken and a POST method that uses CSRFCheck. The first adds a CSRF token to the request, so that the form field can be placed in a visualized view containing the actual token. When this form is submitted, if the CSRF check passes and the submission is valid, something else will happen (usually a redirect). If the submission of the form is not valid, the submission of the form is re-displayed along with any errors, so the user can correct the form and submit it again.
It works great!
However, in the tests we have some problems. To test the controller, you can pass it a fake request in the test. The CSRF check itself can be skipped by adding the nocheck header to the fake request, but the view cannot be displayed because there is no token to create the form field. The test fails with RuntimeException, "The CSRF token (csrf.scala: 51) is missing."
Given that it works when it actually runs, but not in tests, it seems like this should be a problem with the way FakeRequests run in Play tests, but I may be doing something wrong. I implemented CSRF protection as described at http://www.playframework.com/documentation/2.2.1/ScalaCsrf and the testing described at http://www.playframework.com/documentation/2.2.1/ScalaFunctionalTest . I would appreciate any pointers if anyone could check out the protected forms of CSRF.
source share