Search code examples
phpcodeignitercsrf-protection

CSRF Protection Codeigniter generating Random token


I am using codeigniter and I have enabled the csrf in config.php as below.

    $config['csrf_protection']   =  TRUE;
    $config['csrf_token_name']   =  'csrf_token';
    $config['csrf_cookie_name']  =  'csrf_cookie';
    $config['csrf_expire']       =  7200;
    $config['csrf_regenerate']       =  TRUE;

Then to avoid the error "An Error Was Encountered. The action you have requested is not allowed." I have added the following code to every form in web views.

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

This code generates a token and the error was cleared.But the token is same for every page because of <?php echo $this->security->get_csrf_hash(); ?>.

When I view the source code by view source in the web page token is clearly visible.

I want to know is this method prevent csrf? Or I have to generate a random token? Or what is the best way to prevent csrf by codeigniter.


Solution

  • The tokens are random. But, Codeigniter will use the same token value until the CSRF cookie expires OR, if $config['csrf_regenerate'] = TRUE; it will create a new token value on each POST request.

    GET requests (i.e. navigating to some other page on the site) do not generate a new token.