I am Using Jqrgrid with Spring Security but how I send CSRF with JQGrid request
I'm not Spring developer. The solution of your problem depends on the way how you can get the CSRF token. It seems that there are two main ways: the usage of <meta>
with content
equal to ${_csrf.token}
or the usage of getCookie('csrftoken')
.
Let us we follow the part (or this one) of spring documentation and we add <meta>
elements _csrf
and _csrf_header
as following
<!DOCTYPE html>
<html>
<head>
<meta name="_csrf" content="${_csrf.token}"/>
<!-- default header name is X-CSRF-TOKEN -->
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<!-- ... -->
</head>
<!-- ... -->
then we can set security token of Ajax request inside of beforeSend
callback of jQuery.ajax
method:
$.ajax({
url: "someUrl",
...
beforeSend: function(jqXHR) {
xhr.setRequestHeader(
$("meta[name='_csrf_header']").attr("content"),
$("meta[name='_csrf']").attr("content")
);
}
});
On the other side jqGrid makes already internally the Ajax request. Thus you have to use jqGrid callbacks to inform jqGrid to do the same inside of underlying Ajax request. Thus one should use loadBeforeSend
callback of jqGrid:
loadBeforeSend: function(jqXHR) {
var header = $("meta[name='_csrf_header']").attr("content"),
token = $("meta[name='_csrf']").attr("content");
jqXHR.setRequestHeader(header, token);
}
If you would later implement editing of jqGrid data, then you will have to do close things inside of other callbacks, which allows to call setRequestHeader
inside of beforeSend
callback of jQuery.ajax during the editing of the grid.
$('meta[name=csrf]').attr('content')
will get you the CSRF, in another you can usegetCookie('csrftoken')
. To include CSRF in the loading request you can useloadBeforeSend
like in the answer:loadBeforeSend: function(jqXHR) { jqXHR.setRequestHeader('X-CSRF-Token', csrf_token); }
– Oleg Dec 24 '17 at 10:22beforeSend
callback, which you try to use. All unknown callbacks will be just ignored. You can include analert
message in the code ofbeforeSend
to see that it will be never used. The correct name of the isloadBeforeSend
(see my previous comment). – Oleg Dec 24 '17 at 12:29