Send CSRF token inside javascript POST gives error

In my web application, I am using spring security 3.2.x and I am doing CSRF validation. On my login page, I have successfully done this. But inside, I have a button, and the button action is written inside javascript

$('#download').click(function(){ var paramValue = '${params}'; var params = $('#params_').clone() $('<form target="_blank" action="report" method="post"></form>').append(params).appendTo('body').submit().remove(); }); 

Now the problem is when I clicked on this button. He gives the following error.

An invalid CSRF token "null" was found in the request parameter "_csrf" or in the header "X-CSRF-TOKEN".

I think this is because it cannot send the CSRF token . Can someone tell me how to solve this.

Thank you in advance

0
source share
2 answers

Well, the problem was in the next line: I did not send csrf tokens, as in normal form representations.

  $('<form target="_blank" action="report" method="post"></form>').append(params).appendTo('body').submit().remove(); 

So what I did, I created a hidden field and paste it as shown below.

 <script type="text/javascript"> $(document).ready(function () { $('#download').click(function(){ var params = $('#params_').clone(); var csrftoken = $("#csrftoken_").clone(); $('<form target="_blank" action="report" method="post"></form>') .append(params) .append(csrftoken) .appendTo('body') .submit() .remove(); }); }); </script> <input type='hidden' id='params_' name='params' value='${params}' /> <input type="hidden" id="csrftoken_" name="${_csrf.parameterName}" value="${_csrf.token}" /> 

It works....

+1
source

Yes, as you said, this is because your dynamically generated form does not contain a valid CSRF input token. From Spring Security Documentation :

 $(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); }); }); 

This will add the required headers to your ajax requests.

+2
source

All Articles