设置配置项(CSRF)在Codeigniter中不起作用

Bnd*_*ndr 5 php config codeigniter csrf

我只想在几个控制器中打开csrf保护,所以我有

function __construct() {

    parent::__construct();
    $this->load->library('form_validation');        
    $this->load->library('tank_auth');
    $this->load->helper(array('form', 'url'));
    $this->load->model('user_model', '', true);

    $this->config->set_item('csrf_protection', TRUE);

}
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用,尽管当我在页面上执行var_dump($ this-> config)时,它表明csrf_protection为TRUE,但未设置cookie,并且窗体具有一个没有值的隐藏字段

<input type="hidden" name="ci_csrf_token" value="" />

Csrf令牌名称和cookie名称都已设置,使用form_open()调用表单。

任何帮助将非常感激。

更新:由于安全类构造中的这一行,因此从2.1.1版本开始这是不可能的if (config_item('csrf_protection') === TRUE) {

安全类在控制器之前初始化,因此自然而然地改变了控制器中的配置项不会影响它。

Pat*_*lle 5

我为您提供解决方案。创建一个自定义application / core / MY_Security.php并将其放入其中:

<?php if ( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' );

class MY_Security extends CI_Security
{
    public function csrf_verify( )
    {
        foreach ( config_item('csrf_excludes') as $exclude )
        {
            $uri = load_class('URI', 'core');
            if ( preg_match( $exclude, $uri->uri_string() ) > 0 )
            {
                // still do input filtering to prevent parameter piggybacking in the form
                if (isset($_COOKIE[$this->_csrf_cookie_name]) && preg_match( '#^[0-9a-f]{32}$#iS', $_COOKIE[$this->_csrf_cookie_name] ) == 0)
                {
                    unset( $_COOKIE[$this->_csrf_cookie_name] );
                }
                return;
            }
        }
        parent::csrf_verify( );
    }
}
Run Code Online (Sandbox Code Playgroud)

这将检查以下哪些内容需要排除在CSRF部分的application / config.php中:

$config['csrf_excludes'] = array
    ( '@^/?excluded_url_1/?@i'
    , '@^/?excluded_url_2/?@i' );
Run Code Online (Sandbox Code Playgroud)

每个匹配的网址格式都将从CSRF检查中排除。您可以在http://rubular.com上构建正则表达式

干杯