從Spring Security3.2開始,默認就會啟用CSRF攻擊。
Spring Security通過一個同步token的方式來實現CSRF防護。它會攔截狀態變化的請求並檢查CSRF token。如果請求不包含CSRF token,或token不能與服務器端的token相匹配,請求將會失敗,並拋出CsrfException。
Spring Security已經簡化了將token放到請求的屬性中這一任務:
- 使用JSP作為頁面模板的話,要做的事非常類似:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
如果使用Spring表單綁定標簽的話,標簽會自動為我們添加隱藏的CSRF token標簽。
例如一個用from表單提交一個post的請求,想要通過驗證必須添加上:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
下面給一個例子:
<form class="form-new-pwd-wrapper" action="${pageContext.request.contextPath }/resetNew" method="POST"> <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" /> <div class="pwd-input-container-wrapper"> <span class="pwd-title-wrapper">新密碼 :</span> <input id="pwd" class="password-input-wrapper" type="password" name="password" placeholder=" 請輸入新的密碼"> </div> <div class="pwd-input-container-wrapper"> <span class="pwd-title-wrapper">再次輸入:</span> <input id="confirm-pwd" class="password-input-wrapper" type="password" placeholder=" 請再次輸入新的密碼"> </div> <input class="submit-request-wrapper" type="submit" value="確認修改密碼" onclick="return check();"> </form>
如果上屬例子中沒有添加上第二行的代碼,
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
則默認會被系統攔截,進入到預先設置的登錄界面。