項目使用的是 spring-boot + spring-security,頁面用了 thymeleaf 模板。
本該很簡單的一個提交,然而點擊 Submit 后出錯:
提示缺少 “_csrf” 參數或 'X-CSRF-TOKEN' 頭部。
【原因】
使用了 spring-security 后,默認開啟了防止跨域攻擊的功能,任何 POST 提交到后台的表單都要驗證是否帶有 _csrf 參數,一旦傳來的 _csrf 參數不正確,服務器便返回 403 錯誤;
解決方法一:form 表單中添加 _csrf 隱藏域
<form method="post" action="/login">
username: <input type="text" name="userName" />
<br />
password: <input type="password" name="password" />
<br />
<!-- 添加隱藏域 -->
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
<button type="submit">Submit</button>
</form>
以上代碼相對之前代碼,添加了
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}"/>
做為提交到后台的 _csrf 值;
解決方法二(推薦使用):form 表單使用 th:form 屬性, thymeleaf 會自動在 form 表單中生成 _csrf 隱藏域;
<form method="post" th:action="@{/login}">
username: <input type="text" name="userName" />
<br />
password: <input type="password" name="password" />
<br />
<button type="submit">Submit</button>
</form>
解決方法三:關閉防跨域攻擊功能,使用 http.csrf().disable():
package com.shawearn.blog.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
// 省略其他代碼;
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
// 代碼省略...
}
}
摘抄