我在我的网站上启用了 CSRF 保护,但 CSRF 令牌仅在使用
form_close()
时才会放置在隐藏字段中。我通过 ajax 发布数据,还需要发送 CSRF 以防止 500 错误。
我认为有一种方法可以将 CSRF 令牌显式嵌入到页面中,但我似乎找不到它。
页面上没有表单时如何获取CSRF令牌?
您可以通过安全类获取CSRF令牌名称和值:
$this->security->get_csrf_hash();
$this->security->get_csrf_token_name();
以这种方式将其添加到表单中
<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
这是一个向您展示如何启用 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>
对于任何在 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'));
...