Spring security csrf實現前端純html+ajax

spring security集成csrf
進行post等請求時,爲了防止csrf攻擊,須要獲取token才能訪問javascript

所以須要添加html

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>


動態獲取token前端

這樣的話,須要使用jsp或模板引擎java

但又想使用純html+ajax.很難受ajax

最近想到了一個辦法spring

經過ajax獲取token,後端仍使用jsp或freemarker之類的模板引擎後端

但前端可實現純html+ajax,瞬間感受釋放安全

首先定義一個模板_csrf.ftl或_cscf.jsp等,內容爲mvc

<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>

而後寫一個URI,返回的視圖爲_csrf.ftl,以spring mvc爲例app

@RequestMapping(path = "/jsp/common/_csrf",method = RequestMethod.GET)
 public String _csrf(Model model){
      return "/jsp/common/_csrf";
 }

前端將token使用js append到header中,同時設置ajaxSetup的beforeSend,使其發送請求的時候將token放到請求頭、

<script>
$(function () {
function getCsrfToken(){
   $.get("${basePath}/jsp/common/_csrf",function(data){
            $("head").append(data);
            var token = $("meta[name='_csrf']").attr("content");
            var header = $("meta[name='_csrf_header']").attr("content");
            $.ajaxSetup({
                 beforeSend: function (xhr) {
                  if(header && token ){
                      xhr.setRequestHeader(header, token);
                  }
             }
          });
     });
   }
  getCsrfToken()
})
</script> 

 

只要在有post等須要token的請求頁面添加上面的代碼,便可愉快的寫ajax了

最主要的是安全性,不知道這樣能不能保證token不被csrf利用

由於其放置token的位置和使用方式和通常的方式是同樣的,因此暫且認爲是安全的,畢竟請求仍是須要token

相關文章
相關標籤/搜索