Wednesday 26 November 2014

How to test actions annotated with @RequireCSRFCheck in Play Framework 2?

Let say you have an action as below that you want to protect against CSRF attacks, so you add the @RequireCSRFCheck annotation:

@RequireCSRFCheck
public Result saveUser() {
    // Handle body (process a form)
    return ok();
}

Now suppose you want to write some functional tests for this action. All you need to do is to add fake "nocheck" to your header in "callAction" as below:

final Result result = callAction(controllers.routes.ref.UserController.saveUser(),fakeRequest().withHeader("Csrf-Token", "nocheck"));
assertThat(status(result)).isEqualTo(OK);

For more information about CSRF checks in Play Framework 2 see: JavaCsrf

No comments:

Post a Comment