Welcome Guest, Not a member yet? Register   Sign In
Ajax POST and CSRF
#4

If you have the following in your config:

PHP Code:
$config['csrf_regenerate'] = TRUE

then you need to update the CSRF token on each request. When you're using AJAX, this usually means you need to use the get_csrf_token_name() and get_csrf_hash() methods of the security library in your controller and send those values in your response to your AJAX posts, then process them in the success() or done() handler in the JavaScript, so you can send those values with your next AJAX post.

Usually when I need to do something like that, I'll setup the form something like this:

PHP Code:
<form method="post" id="some_form">
    <
input type="hidden" id="csrf" name="<?= $this->security->get_csrf_token_name(); ?>" value="<?= $this->security->get_csrf_hash(); ?>" /> 

This only ensures the values are correct for the first post of the form data, though, since the token name and CSRF hash are only placed in the form when the page is initially loaded. So, the JavaScript would do something like this while processing each response to an AJAX post:

Code:
$('#csrf').val(csrfHashFromResponse);
$('#csrf').attr('name', csrfTokenNameFromResponse);

The post itself also has to include the input, so the CSRF check will pass.
Reply


Messages In This Thread
Ajax POST and CSRF - by sammyci - 02-20-2016, 10:46 AM
RE: Ajax POST and CSRF - by ikarius6 - 02-20-2016, 03:38 PM
RE: Ajax POST and CSRF - by sammyci - 02-20-2016, 08:05 PM
RE: Ajax POST and CSRF - by mwhitney - 02-26-2016, 07:37 AM
RE: Ajax POST and CSRF - by ismaelirc - 07-11-2016, 12:35 PM



Theme © iAndrew 2016 - Forum software by © MyBB