javascript - CSRFGuard: How to inject CSRF token into URL returned by AJAX call -


we attempting add csrf protection our existing java web application using csrfguard. we've followed owasp's guide token injection, , has gotten of way there. we're using dynamic dom manipulation method, , find urls/forms/ajax calls formatted inserted csrf token. our issue this:

parts of pages generated dynamically ajax calls return jspfs. jspfs returned have links never subject csrfguard dom manipulation, , such, don't have csrf token. clicking on links causes csrf violation because no token present.

furthermore, according owasp guide ajax support, dynamic script needs reference prior ajax call ajax call can intercepted , have csrf token inserted header. same script dynamically updates dom. - solve issue posed in question need run script after ajax call, need run before ajax call make in first place. trying run twice causes issues.

what proper solution here? csrfguard javascript file need modified dynamic token injection can run against targeted elements? has issue been solved already?

i had same problem. modified csrfguard.js way:

  1. i moved out functions (function() {}) block , put them before block.
  2. i defined 2 new functions

        function gettokennamevaluepair() {         var xhr = window.xmlhttprequest ? new window.xmlhttprequest : new window.activexobject("microsoft.xmlhttp");         var csrftoken = {};         xhr.open("post", "%servlet_path%", false);         xhr.setrequestheader("fetch-csrf-token", "1");         xhr.send(null);         return xhr.responsetext; }   function injecttokensfornewtags() {     var token_pair = gettokennamevaluepair();            token_pair = token_pair.split(":");     var token_name = token_pair[0];     var token_value = token_pair[1];     injecttokens(token_name, token_value); } 

and ajax returning html chunk links should this:

    $.post(loadurl, function(data) {         $(target).html(data);         injecttokensfornewtags();     }); 

Comments