CodeIgniter use CSRF protection only in some pages

我们两清 提交于 2019-11-29 07:22:18

Now the CI3 have this feature, we can exclude the URIs in the config 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]+'
);

You can do this by editing the config.php file

 $config['csrf_protection'] = FALSE;

Step 1: create an array of pages that you want to protect

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

Step2: check if there is any request for the protected page then set it to 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;
        }
    }

}

Step 3: add this to your views

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

Or simply use the form_open() function to add the hidden CSRF token field automatically.

For a more safer approach, you should switch on CSRF protection at all times and only exempt some pages you wish in an array in the config.php file.

$config['csrf_protection'] = TRUE;

Then set an array of links you wish to exempt from CSRF protection:

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

Now turn those array links CSRF protection off.

if (isset($_SERVER["REQUEST_URI"])) {
    if (in_array($_SERVER["REQUEST_URI"],$csrf_off)) {
        $config['csrf_protection'] = FALSE;
    }
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!