Spring security csrf實現前端純html+ajax

來源:互聯網
上載者:User

標籤:攻擊   nbsp   asc   style   com   返回   ram   請求   sep   

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.