2016-06-17 116 views
3

如何在Play 2.5.4中實現CSRFfilters?播放文檔是錯誤的(不編譯,並且不能在播放2.5.4 java api下),這裏的示例不編譯(Play 2.5 disable csrf protection for some requests)。玩2.5.4 - 如何實現CSRF過濾器?

2.5 java API有一個CRSFFilter類,但它不是EssentialFilter的子類,所以不能添加到EssentialFilters數組中,因爲它是錯誤的類型。

此功能目前是否打破了Play 2.5.4或文檔目前有誤導/錯誤?

回答

1

此代碼適合我,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 
+0

謝謝你,爲我工作。 –