1

I have this form i am posting and I am placing my csrf token like this

controller method

$csrf = array(
        'name' => $this->security->get_csrf_token_name(),
        'hash' => $this->security->get_csrf_hash()
);

passing to view like this

<input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" />

The docs say

Tokens may be either regenerated on every submission (default): https://codeigniter.com/user_guide/libraries/security.html

My question is how the csrf is actually verified. When I use $this->security->get_csrf_hash() when the form is submitted, shall the value be equal to the hash submitted or how will the posted csrf hash be taken as valid?.

Sofyan Thayf
  • 1,322
  • 2
  • 14
  • 26
Gandalf
  • 1
  • 29
  • 94
  • 165
  • Refer to this [Codeigniter CSRF - how does it work](https://stackoverflow.com/q/6244669/6521116) – LF00 Oct 15 '19 at 01:25
  • the hash generated is stored on server as cookie and verified if token submitted for the request is same as what is on server – Boosuro Feb 05 '20 at 05:50

2 Answers2

0

What you have todo is enable it in your $config['csrf_protection'] and use the form_open() function for your form.

CodeIgniter will insert and check the CSRF automatically.

LF00
  • 27,015
  • 29
  • 156
  • 295
  • i guess you shouldn't - because its just a protection method (take a look at https://github.com/bcit-ci/CodeIgniter/blob/develop/system/core/Security.php#L251 - and you see CI exíts with a status 403) – Atural Oct 15 '19 at 09:02
0

You can enable CSRF protection by altering your application/config/config.php file in the following way:

$config['csrf_protection'] = TRUE;

If you use the form helper, then form_open() will automatically insert a hidden csrf field in your forms. If not, then you can use get_csrf_token_name() and get_csrf_hash()

$csrf = array(
        'name' => $this->security->get_csrf_token_name(),
        'hash' => $this->security->get_csrf_hash()
);

<input type="hidden" name="<?=$csrf['name'];?>" value="<?=$csrf['hash'];?>" />

Tokens may be either regenerated on every submission (default) or kept the same throughout the life of the CSRF cookie. The default regeneration of tokens provides stricter security, but may result in usability concerns as other tokens become invalid (back/forward navigation, multiple tabs/windows, asynchronous actions, etc). You may alter this behavior by editing the following config parameter

$config['csrf_regenerate'] = TRUE;

Select URIs can be whitelisted from csrf protection (for example API endpoints expecting externally POSTed content). You can add these URIs by editing the ‘csrf_exclude_uris’ config parameter:

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

Regular expressions are also supported (case-insensitive):

$config['csrf_exclude_uris'] = array(
        'api/record/[0-9]+',
        'api/title/[a-z]+'
);
halfer
  • 19,824
  • 17
  • 99
  • 186
Mujahid Bhoraniya
  • 1,518
  • 10
  • 22