Security Class

The Security Class contains methods that help protect your site against Cross-Site Request Forgery attacks.

Loading the Library

If your only interest in loading the library is to handle CSRF protection, then you will never need to load it,as it runs as a filter and has no manual interaction.

If you find a case where you do need direct access though, you may load it through the Services file:

  1. $security = \Config\Services::security();

Cross-site request forgery (CSRF)

You can enable CSRF protection by altering your app/Config/Filters.phpand enabling the csrf filter globally:

  1. public $globals = [
  2. 'before' => [
  3. //'honeypot'
  4. 'csrf'
  5. ]
  6. ];

Select URIs can be whitelisted from CSRF protection (for example APIendpoints expecting externally POSTed content). You can add these URIsby adding them as exceptions in the filter:

  1. public $globals = [
  2. 'before' => [
  3. 'csrf' => ['except' => ['api/record/save']]
  4. ]
  5. ];

Regular expressions are also supported (case-insensitive):

  1. public $globals = [
  2. 'before' => [
  3. 'csrf' => ['except' => ['api/record/[0-9]+']]
  4. ]
  5. ];

If you use the form helper, thenform_open() will automatically insert a hidden csrf field inyour forms. If not, then you can use the always available csrf_token()and csrf_hash() functions

  1. <input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>" />

Additionally, you can use the csrf_field() method to generate thishidden input field for you:

  1. // Generates: <input type="hidden" name="{csrf_token}" value="{csrf_hash}" />
  2. <?= csrf_field() ?>

When sending a JSON request the CSRF token can also be passed as one of the parameters.The next way to pass the CSRF token is a special Http header that’s name is available bycsrf_header() function.

Additionally, you can use the csrf_meta() method to generate this handymeta tag for you:

  1. // Generates: <meta name="{csrf_header}" content="{csrf_hash}" />
  2. <?= csrf_meta() ?>

The order of checking the avability of the CSRF token is as follows:

  • $_POST array
  • Http header
  • php://input (JSON request) - bare in mind that this approach is the slowest one since we have to decode JSON and then encode it againTokens may be either regenerated on every submission (default) orkept the same throughout the life of the CSRF cookie. The defaultregeneration of tokens provides stricter security, but may resultin usability concerns as other tokens become invalid (back/forwardnavigation, multiple tabs/windows, asynchronous actions, etc). Youmay alter this behavior by editing the following config parameter
  1. public $CSRFRegenerate = true;

When a request fails the CSRF validation check, it will redirect to the previous page by default,setting an error flash message that you can display to the end user. This provides a nicer experiencethan simply crashing. This can be turned off by editing the $CSRFRedirect value inapp/Config/App.php:

  1. public $CSRFRedirect = false;

Even when the redirect value is true, AJAX calls will not redirect, but will throw an error.

Other Helpful Methods

You will never need to use most of the methods in the Security class directly. The following are methods thatyou might find helpful that are not related to the CSRF protection.

sanitizeFilename()

Tries to sanitize filenames in order to prevent directory traversal attempts and other security threats, which isparticularly useful for files that were supplied via user input. The first parameter is the path to sanitize.

If it is acceptable for the user input to include relative paths, e.g. file/in/some/approved/folder.txt, you can setthe second optional parameter, $relative_path to true.

  1. $path = $security->sanitizeFilename($request->getVar('filepath'));