How to add csrf token to ajax request How to add csrf token to ajax request spring spring

How to add csrf token to ajax request


I modified @Prakash Hari Sharma's solution and had the following code that worked for me. Note, th: prefix if using Thymeleaf.

--Header section

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

Ajax script function

......var token = $("meta[name='_csrf']").attr("content"); var header = $("meta[name='_csrf_header']").attr("content");......xhttp.open("POST", "http://localhost:8080/bids?q="+selected,  true);xhttp.setRequestHeader(header, token);xhttp.send();

Hope this helps someone too.


As a complementary to @EdwardoS answer, after you add meta tags to the <head> element:

Thymeleaf:

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

JSP:

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

...you can then do what is suggested in Spring documentation and have all your future ajax to include csrf:

$(function () {    var token = $("meta[name='_csrf']").attr("content");    var header = $("meta[name='_csrf_header']").attr("content");    $(document).ajaxSend(function (e, xhr, options) {        xhr.setRequestHeader(header, token);    });});


In spring documentation, it is also suggested that you do not use csrf token in GET requests for security reasons

"The ability to scope which requests receive the token helps guard against leaking the CSRF token to a third party."

You can therefore filter to pass token only for POST requests with following manner:

$(function() {    var token = $("meta[name='_csrf']").attr("content");    var header = $("meta[name='_csrf_header']").attr("content");    $(document).ajaxSend(function(e, xhr, options) {        if (options.type == "POST") {            xhr.setRequestHeader(header, token);        }    });});

The meta tags in <head> element would be the same as in previous answers:

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