Spring Security CSRF token not working with AJAX call and form sent to the same JSP

I am trying to implement spring security (ver 3.2.3) CSRF token in my project, linking below to links

http://docs.spring.io/autorepo/docs/spring-security/4.0.0.CI-SNAPSHOT/reference/htmlsingle/#csrf http://docs.spring.io/autorepo/docs/spring-security/ 4.0.0.CI-SNAPSHOT / reference / htmlsingle / # the-csrfmetatags-tag

I can integrate the CSRF token into the JSP successfully without calling AJAX. But when I tried the JSP with an AJAX call, getting an "invalid CSRF token exception". After my analysis, I found that the same token is used to call AJAX and submit the form because of this, I get an "invalid CSRF token exception".

Can anyone help me raid this issue. Is there a way to generate two tokens, i.e. one for calling AJAX and one for submitting the form

security.xml

<access-denied-handler ref="accessDenied" /> <intercept-url pattern="/**" access="ROLE_1" /> <form-login default-target-url='/loginUser.htm' always-use-default-target='true' authentication-failure-url='/forms/common/login.jsp?error=true' /> <logout logout-success-url="/forms/common/logout.jsp" invalidate-session="true" delete-cookies="JSESSIONID" /> <session-management invalid-session-url="/forms/common/sessionexpired.jsp" session-authentication-error-url="/forms/common/login.jsp?Error=alreadyLoggedin" > <concurrency-control expired-url="/forms/common/sessionexpired.jsp" max-sessions="1" error-if-maximum-exceeded="true" /> </session-management> <csrf request-matcher-ref="csrfSecurityRequestMatcher"/> </http> <beans:bean class="com.concerto.pg.login.security.CsrfSecurityRequestMatcher" id="csrfSecurityRequestMatcher"/> 

Jsp

 <head> <sec:csrfMetaTags /> <script type="text/javascript" charset="utf-8"> function changeList(id,option){ var csrfParameter = $("meta[name='_csrf_parameter']").attr("content"); var csrfToken = $("meta[name='_csrf']").attr("content"); var institution = document.getElementById("institutionId").value; var data = {}; data[csrfParameter] = csrfToken; data["institutionId"] = option; if(id=="institutionId"){ var result =''; $.ajax({ type: "GET", async: false, url: './getMerchantByInstitution.htm', data: data,//"institutionId=" + option, dataType:'json', success: function (res) { result = res; var htmlVar = ''; for (var i=0; i<result.length; i++){ htmlVar += '<option value="'+result[i]+'">'+result[i]+'</option>'; } htmlVar += '<option value="ALL">ALL</option>'; $('#merchantId').html(htmlVar); } }); } } </script> </head> 
  added below & lt input type = "hidden" name = "$ {_ csrf.parameterName}" value = "$ {_ csrf.token}" / & gt statement in form tag 

Thanks and Regards, Siva

+3
source share
2 answers

I hope this answer below 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 

permanently change the ajax call:

 url: './getMerchantByInstitution.htm', headers: headers, // THIS WAS ADDED data: data,//"institutionId=" + option, dataType:'json', 

Let me know if this works.

+8
source

To make an AJAX / JSON request with CSRF enabled, you must pass the CSRF token as the header of the HTTP request, not a parameter or other data.

On the page, your meta tags should look like this:

 <meta name="_csrf" content="${_csrf.token}"/> <meta name="_csrf_header" content="${_csrf.headerName}"/> 

Then prepare the 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) { // .... }, .... 

Although this is completely up to you, I would recommend using something like JSON.stringify to transfer data, but it depends, of course.

Link 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.

+16
source

Source: https://habr.com/ru/post/1015576/


All Articles