I am trying to implement spring security (ver 3.2.3) CSRF token in my project by referring below links
http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-
This fixed my issue for me:
<meta name="_csrf" th:content="${_csrf.token}"/>
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
using org.thymeleaf.extras:thymeleaf-extras-springsecurity4:3.0.2.RELEASE
To make an AJAX/JSON request with CSRF enabled you have to pass CSRF token as a HTTP Request Header, not a parameter or other data.
On the page, your meta tags should look like these:
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
Then, prepare values somewhere in the JS code:
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
Pass the CSRF token as a header:
$.ajax({
type: "GET",
async: false,
url: './getMerchantByInstitution.htm',
data: "institutionId=" + option,
beforeSend: function(xhr) {
// here it is
xhr.setRequestHeader(header, token);
},
success: function(obj) {
// ....
},
....
Though it's totally up to you, I'd recommend to use something like JSON.stringify to pass the data, but it depends, of course.
The reference is here:
http://docs.spring.io/spring-security/site/docs/3.2.0.CI-SNAPSHOT/reference/html/csrf.html#csrf-include-csrf-token-ajax
Hope this helps.
I hope this below answer helps. Make these changes
var csrfParameter = $("meta[name='_csrf_parameter']").attr("content");
var csrfToken = $("meta[name='_csrf']").attr("content");
var csrfHeader = $("meta[name='_csrf_header']").attr("content"); // THIS WAS ADDED
and after
data[csrfParameter] = csrfToken;
data["institutionId"] = option;
headers[csrfHeader] = csrfToken; // THIS WAS ADDED
finally change in the ajax call:
url: './getMerchantByInstitution.htm',
headers: headers, // THIS WAS ADDED
data: data,//"institutionId=" + option,
dataType:'json',
Let me know if this works.