Play 2.5.4 - how to implement CSRF filters?

☆樱花仙子☆ 提交于 2019-11-29 23:00:47

问题


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?


回答1:


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 


来源:https://stackoverflow.com/questions/37872947/play-2-5-4-how-to-implement-csrf-filters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!