1. 程式人生 > >Spring security csrf實現前端純html+ajax

Spring security csrf實現前端純html+ajax

var light urn span 同時 pan mode eth res

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

因此需要添加

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


動態獲取token

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

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

最近想到了一個辦法

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

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

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

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

然後寫一個URI,返回的視圖為_csrf.ftl,以spring mvc為例

@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

Spring security csrf實現前端純html+ajax