Getting Codeigniter CSRF token without a form?

2019-02-02 00:49发布

问题:

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?

回答1:

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

$this->security->get_csrf_hash();
$this->security->get_csrf_token_name();


回答2:

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(); ?>">


回答3:

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>