此代碼適合我,Play 2.5.4 Java。 創建應用程序/ Filters.java文件,並把這個
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()
};
}
}
添加過濾器依賴於build.sbt
libraryDependencies += filters
,並在您application.conf把
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
}
您可以瞭解更多關於這裏的配置https://www.playframework.com/documentation/2.5.x/resources/confs/filters-helpers/reference.conf
在你的模板文件只需要導入幫手
@import helper._
然後用它在你的表格是這樣
<form method="POST" action="...">
@CSRF.formField
謝謝你,爲我工作。 –