Spring Security Csrf Token Not Working With Ajax Call & Form Submit In Same Jsp
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-SNAPSHOT/refere
Solution 1:
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:
Hope this helps.
Solution 2:
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 ADDEDdata: data,//"institutionId=" + option,
dataType:'json',
Let me know if this works.
Solution 3:
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
Post a Comment for "Spring Security Csrf Token Not Working With Ajax Call & Form Submit In Same Jsp"