Protect your Play! application with the CSRF filter
11 Feb 2013
Play! 2.1 introduces a new filters API and Cross Site Request Forgery (CSRF) protection. The CSRF filter is not well documented and it took a while to work out how to enable it in my Play! application. It took a bit of digging through the Play! source code and looking through the CSRF tests to work out how to use the CSRF filter. Below is a summary of what is required to protect your Play! 2.1 application with the new CSRF filter.
First of all add the filters module to your app dependencies in appname/project/Build.scala.
Next create appname/app/Global.scala and extend the Global settings so that it uses the CSRF filter.
Now the CSRF tests will convey that you need to do the following in all your controllers that return a view with a form post.
and use the CSRF token in your view template as follows.
Relax you don’t have to call CSRF.getToken() in all of your controllers that present a form. Fortunately there is a CSRF view helper that takes an implicit token so that you won’t need to set up the token in your controller and pass it to the view. Instead you just have to declare the implicit token in the view and wrap your post action with the CSRF helper function as follows.