What I want to do is to protect some sensitive forms from CSRF
attack in codeigniter
but not all pages.
To protect from CSRF
if I set it in config.php it applies for all pages. is there any way to do that only for some pages by setting in controller?
$config['csrf_protection'] = TRUE;
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;
}
}
来源:https://stackoverflow.com/questions/18378688/codeigniter-use-csrf-protection-only-in-some-pages