In my web application I'm using spring security 3.2.x and I'm doing CSRF validation. In my login page I have successfully done this. But inside, I have a button and the button action is written inside a 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 that button It gives the following error
Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
I thinkthis is because It's fail to send the CSRF token. Can anybody tell me how to solve this.
Thanks in advance
In my web application I'm using spring security 3.2.x and I'm doing CSRF validation. In my login page I have successfully done this. But inside, I have a button and the button action is written inside a 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 that button It gives the following error
Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
I thinkthis is because It's fail to send the CSRF token. Can anybody tell me how to solve this.
Thanks in advance
Share Improve this question asked Mar 25, 2014 at 10:12 RavinduRavindu 2,5609 gold badges31 silver badges46 bronze badges2 Answers
Reset to default 2Yes, as you said it is because your dynamically created form does not contain valid CSRF token input. 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 required headers to your ajax requests.
Ok, I problem was in the following line I didn't send the csrf tokens like in the normal form submissions.
$('<form target="_blank" action="report" method="post"></form>').append(params).appendTo('body').submit().remove();
So what I did is I created the hidden field and insert it like bellow.
<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}" />
This works....