[spring-security]添加form表單通過post前期 提交到後端,請求提示403

添加form表單通過post前期 提交到後端,請求提示403

problem

使用了spring-security,添加form表單通過post前期 提交到後端,請求提示403
image-20211229092838683

solution1

思路:

  • 禁止csrf可以解決問題
  • 默認開啓狀態
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable(); // 禁止csrf 
        // ....
    }
}

solution2

思路:

  • spring security不關閉csrf驗證
  • 表單添加csrf 信息

form添加_csrf相關字段

<p>期望有csrf驗證:form</p>
<form action="/product/add" method="post">
    <p><input type="hidden"  name="_csrf" th:value="${_csrf.token}"/></p>
    <p><span>name:</span><input name="name" placeholder="name" value="蘋果"/></p>
    <p><span>age:</span><input  name="price" placeholder="price" value="6"/></p>
    <p><input type="submit"/></p>
</form>

ajax方式

思路:

  • spring security不關閉csrf驗證
  • 在ajax請求中加入data中
<!-- input中加入csrf token信息 -->
<p><input type="hidden"  name="_csrf" th:value="${_csrf.token}"/></p>
<!-- ajax請求post數據data中加上這個csrf token即可 -->
<script>
    data: {
        "_csrf": $("input[name='_csrf']").attr("value"),
        "name": "test"
    }
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章