Welcome Guest, Not a member yet? Register   Sign In
Multple CSRF token?
#3

Hi rakibtg,

I recently ran into this dilemma and the solution that I went with is as follows:

- When the page loads, echo the first token into a hidden input in the form.
- On each ajax request (first & thereafter) send a new token in the response headers
- Store that token for use with the next request

I used $.ajaxSetup() to add the token to each AJAX call and the $.ajaxSuccess() to store the new token on each AJAX response. Here are some code samples to give you a better idea:

1. Ajax_Controller.php (receives ajax calls from browser)

PHP Code:
header('CI-CSRF-Token: '$this->input->security->get_csrf_hash()); // pass a new token back on each request 

2. ajax-helper.js (loaded on every page that uses ajax calls)
Code:
//Setup AJAX to use the first token from the hidden input - see footer.php
$(function($) {    
    $.ajaxSetup({
        data: {
            csrf_test_name : $('#csrf').val()
        }
    });
});

//Update CSRF token on any ajax request so we're all good for the next one
$(document).ajaxSuccess(function(event, jqXHR, settings) {    

    resetAjaxToken(jqXHR);

});

//Get the token from an AJAX response and re-setup AJAX to send the new token.
function resetAjaxToken(jqXHR) {

   var token = jqXHR.getResponseHeader("CI-CSRF-Token");

   $.ajaxSetup({
       data: {
           csrf_test_name : token
       }
   });
}

3. footer.php (Common footer for all pages, so all pages include an initial CSRF)

PHP Code:
<input type="hidden" id="csrf" name="<?= $csrf->name; ?>" value="<?= $csrf->hash; ?>" /> 

Obviously, this is only required if you're using CSRF regeneration but it sounds like you are. To me, this seems the most secure method and doesn't require you to disable CSRF etc.

Let me know if that make sense!

Dave
Reply


Messages In This Thread
Multple CSRF token? - by rakibtg - 02-21-2015, 04:50 AM
RE: Multple CSRF token? - by Avenirer - 02-22-2015, 01:51 PM
RE: Multple CSRF token? - by 02DClarke - 02-22-2015, 05:58 PM
RE: Multple CSRF token? - by rakibtg - 03-01-2015, 03:30 AM
RE: Multple CSRF token? - by spjonez - 03-01-2015, 10:52 AM
RE: Multple CSRF token? - by rakibtg - 03-03-2015, 11:02 AM
RE: Multple CSRF token? - by nasser.man - 04-06-2015, 12:06 PM



Theme © iAndrew 2016 - Forum software by © MyBB