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

问题描述 投票:6回答:3

我想要做的是保护一些敏感形式免受CSRF中的codeigniter攻击但不是所有页面。

如果我在config.php中设置它以保护CSRF它适用于所有页面。是否有任何方法只通过在控制器中设置一些页面?

$config['csrf_protection'] = TRUE;
codeigniter codeigniter-2 csrf
3个回答
10
投票

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

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


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

8
投票

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

 $config['csrf_protection'] = FALSE;

第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;
        }
    }

}

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

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

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


1
投票

为了更安全的方法,您应该始终打开CSRF保护,并且只在config.php文件中的数组中免除您希望的某些页面。

$config['csrf_protection'] = TRUE;

然后设置一组您希望免除CSRF保护的链接:

$csrf_off = array(
    "/api",
    "/api/example",
    "/somelink/something/example"
    );

现在关闭那些阵列链接CSRF保护。

if (isset($_SERVER["REQUEST_URI"])) {
    if (in_array($_SERVER["REQUEST_URI"],$csrf_off)) {
        $config['csrf_protection'] = FALSE;
    }
} 
© www.soinside.com 2019 - 2024. All rights reserved.