Spring Security Integrated CSRF
To prevent CSRF attacks, you need to obtain token to access the post and other requests.
So you need to add
<input type= "hidden" name= "${_csrf.parametername}" value= "${_csrf.token}"/>
Get tokens Dynamically
In this case, you need to use the JSP or template engine
But also want to use pure html+ajax. It's hard to be
I've been thinking about a way
Get tokens through Ajax, and the backend still uses a template engine like JSP or Freemarker
But the front end can realize pure html+ajax, instantaneous feeling release
First define a template _CSRF.FTL or _cscf.jsp, etc., content is
<meta name= "_csrf" content= "${_csrf.token}"/><meta name= "_csrf_header" content= "${_csrf.headerName}"/>
Then write a URI, return the view as _CSRF.FTL, take spring MVC as an example
@RequestMapping (Path = "/jsp/common/_csrf", method = requestmethod.get) public String _CSRF (model model) {return "/jsp /COMMON/_CSRF "; }
The front end will use the token JS append to the header, while setting the Ajaxsetup beforesend, so that it sends the request when the token is placed in the request header,
<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>
Just add the code on the request page with the post and so on, and you'll be able to write Ajax happily.
The main thing is security, and I don't know if it's going to make sure tokens aren't used by CSRF.
Because the location and use of the token is the same as in the general way, it is considered safe for the moment, after all, the request still needs token.
Spring security csrf for front-end pure Html+ajax