Reputation: 33
How does one implement CSRFfilters in Play 2.5.4? The play documentation is wrong (doesn't compile, and can't under the play 2.5.4 java api), the example here doesn't compile (Play 2.5 disable csrf protection for some requests).
the 2.5 java API has a CRSFFilter class but it is not a sub class of EssentialFilter so cannot be added to the array of EssentialFilters because it is the wrong type.
Is this functionality currently broken for Play 2.5.4 or is the documentation currently misleading/wrong?
Upvotes: 3
Views: 2928
Reputation: 487
This code works fine for me, Play 2.5.4 Java. Create app/Filters.java file and put this
import javax.inject.*;
import play.*;
import play.mvc.EssentialFilter;
import play.http.HttpFilters;
import play.mvc.*;
import play.filters.csrf.CSRFFilter;
public class Filters implements HttpFilters {
private CSRFFilter csrfFilter;
@Inject
public Filters(
CSRFFilter csrfFilter) {
this.csrfFilter = csrfFilter;
}
@Override
public EssentialFilter[] filters() {
return new EssentialFilter[] {
csrfFilter.asJava()
};
}
}
add filters dependency in build.sbt
libraryDependencies += filters
and in your application.conf put
play.modules.enabled += "play.filters.csrf.CSRFModule"
# CSRF config
play.filters.csrf {
token {
name = "csrfToken"
sign = true
}
cookie {
name = null
secure = ${play.http.session.secure}
httpOnly = false
}
body.bufferSize = ${play.http.parser.maxMemoryBuffer}
bypassCorsTrustedOrigins = true
header {
name = "Csrf-Token"
protectHeaders {
Cookie = "*"
Authorization = "*"
}
bypassHeaders {}
}
method {
whiteList = ["GET", "HEAD", "OPTIONS"]
blackList = []
}
contentType {
whiteList = []
blackList = []
}
errorHandler = null
}
You can learn more about configuration here https://www.playframework.com/documentation/2.5.x/resources/confs/filters-helpers/reference.conf
In your template files just import helper
@import helper._
Then use it in your forms like this
<form method="POST" action="...">
@CSRF.formField
Upvotes: 1