17

I have CSRF protection enabled on my site, but the only time the CSRF token is placed in a hidden field is when form_close() is used. I am posting data via ajax and need to send the CSRF as well to prevent the 500 errors.

I thought there was a way to explicitly embed the CSRF token into the page, but I can't seem to find it.

How can I get the CSRF token when there isn't a form on the page?

Motive
  • 3,071
  • 9
  • 40
  • 63
  • [Ajax form + CSRF results in a failing request](http://ellislab.com/forums/viewthread/230264/#1042793) – Sam Arul Raj T Apr 05 '13 at 19:19
  • Sam in incorrect, set the token on the page via $this->security->get_csrf_hash(); and then just pull the _TOKEN value, ex. data: { _TOKEN: $('input[name="_TOKEN"]').val()}, – tibc-dev Feb 16 '14 at 18:02

3 Answers3

44

You can get the CSRF token name and value via the security class:

$this->security->get_csrf_hash();
$this->security->get_csrf_token_name();
Narf
  • 14,600
  • 3
  • 37
  • 66
  • 5
    Weird, couldn't find that in the documentation, but that's exactly what I was looking for. thanks – Motive Nov 14 '12 at 21:49
12

Add it to the form this way

<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
Rayiez
  • 1,420
  • 19
  • 20
0

Here is an example that shows you how to enable CSRF Attack mode :

<script>
    
  var cct = '<?php echo $this->security->get_csrf_hash() ?>';
  var get_csrf_token_name = '<?php echo $this->security->get_csrf_token_name() ?>';
  
   $.ajaxSetup({
   type:'post',
  data:{ <?php echo $this->security->get_csrf_token_name() ?> :cct}
   });
   
  
    var siteurl = '<?= site_url()?>';        
       
   </script>
Mohammad Heydari
  • 3,933
  • 2
  • 26
  • 33