播放2.5.4 - 如何实施CSRF过滤器?

时间:2016-06-17 04:04:20

标签: playframework csrf-protection

如何在Play 2.5.4中实现CSRFfilters?播放文档是错误的(没有编译,并且不能在play 2.5.4 java api下),这里的例子没有编译(Play 2.5 disable csrf protection for some requests)。

2.5 java API有一个CRSFFilter类,但它不是EssentialFilter的子类,所以不能添加到EssentialFilters数组中,因为它是错误的类型。

Play 2.5.4目前是否已破解此功能,还是目前误导/错误的文档?

1 个答案:

答案 0 :(得分:1)

此代码适用于我,Play 2.5.4 Java。 创建app / 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