Welcome Guest, Not a member yet? Register   Sign In
*Tip:CSRF + Ajax
#1

(This post was last modified: 12-23-2015, 01:42 PM by BrendanRehman.)

Hi Guys,

This is a quick post on how to setup CSRF protection and Ajax in your CI app. When you set the
PHP Code:
$config['csrf_protection'] = TRUE
to TRUE every form you POST to a controller method has an auto generated CSRF token.

So here's the fix for when you want this to work with all your Ajax calls.

1. Add following code inside your html head tag in your master template or where ever you will be using ajax.

PHP Code:
<?php
        $csrf 
= array(
 
           'name' => $this->security->get_csrf_token_name(),
 
           'hash' => $this->security->get_csrf_hash());
 
       ?>

<input id="app_csrf" type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" /> 

2. Setup your ajax, this happens before any ajax requests are made.

Code:
<script>
   $.ajaxSetup({
       data: {
           csrf_test_name: $("input[id='app_csrf']").val()
       }
   });
</script>

Voila! You're done, all your ajax requests are CSRF protected.

Enjoy,
Brendan
Reply




Theme © iAndrew 2016 - Forum software by © MyBB