As Brad's answerBrad's answer suggests, you can conditionally enable or disable CSRF production via the General Config, based on any criteria you want.
Some use cases might be:
match a
SERVER['REQUEST_URI']
string or substring, to open up a particular set of controllers or actionscheck the
$_SERVER['REMOTE_ADDR']
, to allow token-less requests from a particular IP or IP rangevalidate 'safe' requests based on a key or encrypted timestamp from some
$_POST[]
or$_GET[]
variable
For cleanliness, I typically try to tuck the checking/validation logic away into its own "handler" class. Then, in the general.php
, I set the enableCsrfProduction
item based on the result of the check...
(In MyRequestHelper.php, something like...)
<?php
namespace Craft;
class MyRequestHelper
{
public static function isApiRequest()
{
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
return strpos($path, 'actions/my-api') == 1;
}
}
(In craft/config/general.php, something like...)
require_once (..path/to/MyRequestHelper.php');
$isApiRequest = \Craft\MyRequestHelper::isApiRequest();
return [
// ...other configs...
'enableCsrfProtection' => !$isApiRequest,
];