I am having a challenge implementing csrf protection on two projects based on CI 3.x. As far as I know, my code is not unconventional. Submission of any form results in:
PHP Code:
An Error Was Encountered
The action you have requested is not allowed.
I have looked at numerous solutions to such a problem posted on the web
- I am using form_open() as required for CI to automatically insert the csrf token;
- config elements for crsf and cookies meet the requirements
Here are portions of config.php:
PHP Code:
$config['base_url'] = 'http://betasite.lh.com/';
Session Variables:
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
Cookie Related Variables:
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '.betasite.lh.com';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
Cross Site Request Forgery:
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrftoken';
$config['csrf_cookie_name'] = 'csrfcookie';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
What is the process of generating the token, setting it in a cookie and posting it in the hidden field in a form? Logically, is it?:
- generate token
- save it to cookie
- read token from cookie into $this->crsf_hash
- place token in form so it appears in $_POST at time of form submission
I ask because stepping through the code with xdebug I am seeing inconsistencies. Running a log-in without debugging and it will always fail. On some occasions - maybe 1 out of 8 - if I step through function csrf_verify (Security.php, version CI 3.1.6) the verification passes for the hash in the cookie and the value in $_POST match. The log-in completes as it should.
Since `$config['csrf_regenerate'] = TRUE;` is it necessary to set the csrf cookie in the controller for my application?
Thank you for taking the time to read this.