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
 
                    
                     
                    
                 
                    
                 
         
