Welcome Guest, Not a member yet? Register   Sign In
csrf, ajax and form
#5

(This post was last modified: 08-09-2017, 12:23 PM by Shawn.)

(08-05-2017, 06:16 AM)theedo Wrote:
(08-05-2017, 05:29 AM)InsiteFX Wrote: Google Search is your friend.

You can try this, it uses the jQuery Cookie Plugin was written for CodeIgniter 2.x
but should still work with the 3.x versions.

You will need to download the jQuery Plugin.

Here is the article and code.

CodeIgniter CSRF Protection With Ajax

uh, it solves me the problem. I haven't found this page when I searched on google.. 

However, why the csrf_regenerate is so important?

Once you post data either by traditional post or within an AJAX call the csrf is outdated and must be regenerated from the server. Otherwise it is useless because it is open to forgery. The CI server will not accept the same token twice.  This is managed automatically when you use CodeIgniter form helpers and you are regenerating your page and form from CI. But with ajax you have to do it manually. In your ajax controller you need to regenerate and pass back a new token:
Code:
$ajax_data['csrf_hash'] = $this->security->get_csrf_hash();
echo json_encode($ajax_data);

You will need a way to store the token name and hash value that is sent from the ajax controller. The following view code creates a hidden field to store the name and hash.
Code:
<input type="hidden" name=<?php echo json_encode($this->security->get_csrf_token_name()); ?> value=<?php echo json_encode($this->security->get_csrf_hash()); ?>

Note: If your page also contains a non-ajax CI form it will automatically create the hidden field with this csrf token name.
Everytime you do an ajax post you will need to update this hidden field
Reply


Messages In This Thread
csrf, ajax and form - by theedo - 08-05-2017, 05:15 AM
RE: csrf, ajax and form - by InsiteFX - 08-05-2017, 05:29 AM
RE: csrf, ajax and form - by theedo - 08-05-2017, 06:16 AM
RE: csrf, ajax and form - by Shawn - 08-09-2017, 12:20 PM
RE: csrf, ajax and form - by InsiteFX - 08-05-2017, 09:16 AM



Theme © iAndrew 2016 - Forum software by © MyBB