Getting Codeigniter CSRF token without a form?
Asked Answered
S

4

18

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?

Snowcap answered 14/11, 2012 at 20:50 Comment(2)
Ajax form + CSRF results in a failing requestOutbreed
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()},Stockinet
M
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();
Masaryk answered 14/11, 2012 at 20:57 Comment(1)
Weird, couldn't find that in the documentation, but that's exactly what I was looking for. thanksSnowcap
B
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(); ?>">
Benzaldehyde answered 2/2, 2015 at 11:0 Comment(0)
F
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>
Forsyth answered 18/7, 2017 at 0:40 Comment(0)
G
0

For anyone looking for an answer in 2023.

I solved this by adding protected \CodeIgniter\Security\Security $security; property into my BaseController class, and assigning the core security class into the property when the initController method is called.

...
// Do Not Edit This Line
parent::initController($request, $response, $logger);

// Preload any models, libraries, etc, here.
$this->security = new Security(config('Security'));
...
Geosynclinal answered 10/12, 2023 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.