我在Spring MVC應用程序中使用了Spring Security 3.2.3,並且出現了一些意外的行爲。無法使用Spring Security創建CSRF令牌
按照documentation here,應該儘可能使用${_csrf.token}
在我的HTML的meta標籤:
<meta name="_csrf" content="${_csrf.token}" />
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}" />
從我解壓的「內容」值使用JQuery,並將其放入請求頭使用AJAX。
由於某種原因,雖然Spring Security不會將其轉換爲實際的標記,但它只是作爲字符串「$ {_ csrf.token}」發送到標頭中。
根據文檔,嘗試使用${_csrf.token}
作爲隱藏輸入的備用路徑,然後通過檢查輸入的值來試圖檢查令牌的計算結果,但它仍然只是純文本「$ {_ csrf.token}」 。
由於Spring Security似乎沒有生效,我是否缺少某種配置?我目前使用準系統春季安全Java配置(而不是XML)如下所示:
import org.springframework.context.annotation.*;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.*;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf();
}
}
我知道配置,因爲我把調試語句在它獲取調用,所以我認爲CSRF保護確實是因爲它應該是默認的。
我意識到語法「$ {}」是JSP表達式語言,和我目前成功地用它來評估方面與Thymeleaf的對象,例如:
th:object="${context}"
所以我嘗試添加「日:」在meta標籤的「內容」的前面,像這樣:
<meta name="_csrf" th:content="${_csrf.token}"/>
但它導致一個例外,這不能評價:
異常評估SpringEL的表情:「_csrf.token」
我認爲這裏的密鑰可以搞清楚如何得到表達我的觀點正確評價。
是否有可能「$ {_ csrf.token}」語法只能在JSP中使用,而不能在.html文件中使用? – starmandeluxe
現在的問題是,在運行Spring Security的時候,即使我們已經設置了認證方法,它也很煩人地想要認證用戶,所以我得到了未經授權的錯誤。我需要找出如何繞過Spring Security的默認認證要求...似乎沒有簡單的方法來關閉它,如果您不包含認證配置,整個應用程序拒絕運行(瘋狂!)。我只想從這個框架中獲得CSRF功能!將繼續調查如何繞過... – starmandeluxe
所以經過反覆測試,似乎Spring Security運行,但我仍然只獲得$ {_ csrf.token}的字符串。當JSP需要評估值時,我認爲它與我使用.html文件有關,但將其更改爲.jsp文件會導致「org.thymeleaf.exceptions.TemplateInputException:解析模板{myapplication}時出錯,模板可能不存在或可能無法通過任何已配置的模板解析器訪問「 – starmandeluxe