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