CodeIgniter仅在某些页面中使用CSRF保护

esr*_*pim 6 codeigniter csrf codeigniter-2

我想要做的是保护一些敏感表单免受CSRF攻击,codeigniter但不是所有页面.

为了防止CSRF我在config.php中设置它,它适用于所有页面.是否有任何方法只通过在控制器中设置一些页面?

$config['csrf_protection'] = TRUE;
Run Code Online (Sandbox Code Playgroud)

Bir*_*ira 11

现在CI3具有此功能,我们可以在配置中排除URI http://www.codeigniter.com/userguide3/libraries/security.html?highlight=csrf#cross-site-request-forgery-csrf

$config['csrf_exclude_uris'] = array('api/person/add');


$config['csrf_exclude_uris'] = array(
    'api/record/[0-9]+',
    'api/title/[a-z]+'
);
Run Code Online (Sandbox Code Playgroud)


sha*_*hah 9

您可以通过编辑config.php文件来完成此操作

 $config['csrf_protection'] = FALSE;
Run Code Online (Sandbox Code Playgroud)

第1步:创建要保护的页面数组

例如. $csrf_pages = array('login','test');

步骤2:检查是否有对受保护页面的请求,然后将其设置为TRUE;

if (isset($_SERVER["REQUEST_URI"])) {
    foreach ($csrf_pages as $csrf_page){
        if(stripos($_SERVER["REQUEST_URI"],$csrf_page) !== FALSE) {
            $config['csrf_protection'] = TRUE;
            break;
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

第3步:将其添加到您的视图中

<input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash();?>" />
Run Code Online (Sandbox Code Playgroud)

或者只需使用form_open()函数自动添加隐藏的CSRF令牌字段.