无需表单即可获取 Codeigniter CSRF 令牌?

问题描述 投票:0回答:4

我在我的网站上启用了 CSRF 保护,但 CSRF 令牌仅在使用

form_close()
时才会放置在隐藏字段中。我通过 ajax 发布数据,还需要发送 CSRF 以防止 500 错误。

我认为有一种方法可以将 CSRF 令牌显式嵌入到页面中,但我似乎找不到它。

页面上没有表单时如何获取CSRF令牌?

php ajax codeigniter
4个回答
44
投票

您可以通过安全类获取CSRF令牌名称和值:

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

12
投票

以这种方式将其添加到表单中

<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">

0
投票

这是一个向您展示如何启用 CSRF 攻击模式的示例:

<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>


0
投票

对于任何在 2023 年寻找答案的人。

我通过将

protected \CodeIgniter\Security\Security $security;
属性添加到我的
BaseController
类中,并在调用
initController
方法时将核心安全类分配到该属性中解决了这个问题。

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

// Preload any models, libraries, etc, here.
$this->security = new Security(config('Security'));
...
© www.soinside.com 2019 - 2024. All rights reserved.