Class SecurityComponent
The Security Component creates an easy way to integrate tighter security in your application. It provides methods for various tasks like:
- Restricting which HTTP methods your application accepts.
- Form tampering protection
- Requiring that SSL be used.
- Limiting cross controller communication.
Link: http://book.cakephp.org/3.0/en/controllers/components/security.html
Constants
- 
          
          DEFAULT_EXCEPTION_MESSAGE ¶'The request has been black-holed'Default message used for exceptions thrown 
Property Summary
- 
        $_action protectedstringHolds the current action of the controller 
- 
        $_componentMap protectedarrayA component lookup table used to lazy load component objects. 
- 
        $_config protectedarrayRuntime config 
- 
        $_configInitialized protectedboolWhether the config property has already been configured with defaults 
- 
        $_defaultConfig protectedarrayDefault config 
- 
        $_registry protectedCake\Controller\ComponentRegistryComponent registry class used to lazy load components. 
- 
        $components publicarrayOther Components this component uses. 
- 
        $request publicCake\Network\RequestRequest object 
- 
        $response publicCake\Network\ResponseResponse object 
- 
        $session publicCake\Network\SessionThe Session object 
Method Summary
- 
          __construct() publicConstructor 
- 
          __debugInfo() publicReturns an array that can be used to describe the internal state of this object. 
- 
          __get() publicMagic method for lazy loading $components. 
- 
          _authRequired() protected deprecatedCheck if authentication is required 
- 
          _callback() protectedCalls a controller callback method 
- 
          _configDelete() protectedDelete a single config key 
- 
          _configRead() protectedRead a config variable 
- 
          _configWrite() protectedWrite a config variable 
- 
          _debugCheckFields() protectedIterates data array to check against expected 
- 
          _debugExpectedFields() protectedGenerate debug message for the expected fields 
- 
          _debugPostTokenNotMatching() protectedCreate a message for humans to understand why Security token is not matching 
- 
          _fieldsList() protectedReturn the fields list for the hash calculation 
- 
          _hashParts() protectedReturn hash parts for the Token generation 
- 
          _matchExistingFields() protectedGenerate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset 
- 
          _requireMethod() protectedSets the actions that require a $method HTTP request, or empty for all actions 
- 
          _secureRequired() protectedCheck if access requires secure connection 
- 
          _sortedUnlocked() protectedGet the sorted unlocked string 
- 
          _throwException() protectedCheck debug status and throw an Exception based on the existing one 
- 
          _unlocked() protectedGet the unlocked string 
- 
          _validToken() protectedCheck if token is valid 
- 
          _validatePost() protectedValidate submitted form 
- 
          blackHole() publicBlack-hole an invalid request with a 400 error or custom callback. If SecurityComponent::$blackHoleCallback is specified, it will use this callback by executing the method indicated in $error 
- 
          config() publicUsage
- 
          configShallow() publicMerge provided config with existing config. Unlike config()which does a recursive merge for nested keys, this method does a simple merge.
- 
          generateToken() publicManually add form tampering prevention token information into the provided request object. 
- 
          implementedEvents() publicEvents supported by this component. 
- 
          initialize() publicConstructor hook method. 
- 
          log() publicConvenience method to write a message to Log. See Log::write() for more information on writing to logs. 
- 
          requireAuth() public deprecatedSets the actions that require whitelisted form submissions. 
- 
          requireSecure() publicSets the actions that require a request that is SSL-secured, or empty for all actions 
- 
          startup() publicComponent startup. All security checking happens here. 
Method Detail
__construct() ¶ public
__construct(Cake\Controller\ComponentRegistry $registry, array $config = [])Constructor
Parameters
- 
                Cake\Controller\ComponentRegistry$registry
- A ComponentRegistry this component can use to lazy load its components 
- 
                array$config optional
- Array of configuration settings. 
__debugInfo() ¶ public
__debugInfo(): arrayReturns an array that can be used to describe the internal state of this object.
Returns
array__get() ¶ public
__get(string $name): mixedMagic method for lazy loading $components.
Parameters
- 
                string$name
- Name of component to get. 
Returns
mixedA Component object or null.
_authRequired() ¶ protected
_authRequired(Cake\Controller\Controller $controller): boolCheck if authentication is required
Parameters
- 
                Cake\Controller\Controller$controller
- Instantiating controller 
Returns
booltrue if authentication required
_callback() ¶ protected
_callback(Cake\Controller\Controller $controller, string $method, array $params = []): mixedCalls a controller callback method
Parameters
- 
                Cake\Controller\Controller$controller
- Instantiating controller 
- 
                string$method
- Method to execute 
- 
                array$params optional
- Parameters to send to method 
Returns
mixedController callback method's response
Throws
Cake\Network\Exception\BadRequestExceptionWhen a the blackholeCallback is not callable.
_configDelete() ¶ protected
_configDelete(string $key): voidDelete a single config key
Parameters
- 
                string$key
- Key to delete. 
Returns
voidThrows
Cake\Core\Exception\Exceptionif attempting to clobber existing config
_configRead() ¶ protected
_configRead(string|null $key): mixedRead a config variable
Parameters
- 
                string|null$key
- Key to read. 
Returns
mixed_configWrite() ¶ protected
_configWrite(string|array $key, mixed $value, bool|string $merge = false): voidWrite a config variable
Parameters
- 
                string|array$key
- Key to write to. 
- 
                mixed$value
- Value to write. 
- 
                bool|string$merge optional
- True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false. 
Returns
voidThrows
Cake\Core\Exception\Exceptionif attempting to clobber existing config
_debugCheckFields() ¶ protected
_debugCheckFields(array $dataFields, array $expectedFields = [], string $intKeyMessage = '', string $stringKeyMessage = '', string $missingMessage = ''): arrayIterates data array to check against expected
Parameters
- 
                array$dataFields
- Fields array, containing the POST data fields 
- 
                array$expectedFields optional
- Fields array, containing the expected fields we should have in POST 
- 
                string$intKeyMessage optional
- Message string if unexpected found in data fields indexed by int (not protected) 
- 
                string$stringKeyMessage optional
- Message string if tampered found in data fields indexed by string (protected) 
- 
                string$missingMessage optional
- Message string if missing field 
Returns
arrayMessages
_debugExpectedFields() ¶ protected
_debugExpectedFields(array $expectedFields = [], string $missingMessage = ''): stringGenerate debug message for the expected fields
Parameters
- 
                array$expectedFields optional
- Expected fields 
- 
                string$missingMessage optional
- Message template 
Returns
stringError message about expected fields
_debugPostTokenNotMatching() ¶ protected
_debugPostTokenNotMatching(Cake\Controller\Controller $controller, array $hashParts): stringCreate a message for humans to understand why Security token is not matching
Parameters
- 
                Cake\Controller\Controller$controller
- Instantiating controller 
- 
                array$hashParts
- Elements used to generate the Token hash 
Returns
stringMessage explaining why the tokens are not matching
_fieldsList() ¶ protected
_fieldsList(array $check): arrayReturn the fields list for the hash calculation
Parameters
- 
                array$check
- Data array 
Returns
array_hashParts() ¶ protected
_hashParts(Cake\Controller\Controller $controller): arrayReturn hash parts for the Token generation
Parameters
- 
                Cake\Controller\Controller$controller
- Instantiating controller 
Returns
array_matchExistingFields() ¶ protected
_matchExistingFields(array $dataFields, array $expectedFields, string $intKeyMessage, string $stringKeyMessage): arrayGenerate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset
Parameters
- 
                array$dataFields
- Fields array, containing the POST data fields 
- 
                array$expectedFields
- Fields array, containing the expected fields we should have in POST 
- 
                string$intKeyMessage
- Message string if unexpected found in data fields indexed by int (not protected) 
- 
                string$stringKeyMessage
- Message string if tampered found in data fields indexed by string (protected) 
Returns
arrayError messages
_requireMethod() ¶ protected
_requireMethod(string $method, array $actions = []): voidSets the actions that require a $method HTTP request, or empty for all actions
Parameters
- 
                string$method
- The HTTP method to assign controller actions to 
- 
                array$actions optional
- Controller actions to set the required HTTP method to. 
Returns
void_secureRequired() ¶ protected
_secureRequired(Cake\Controller\Controller $controller): boolCheck if access requires secure connection
Parameters
- 
                Cake\Controller\Controller$controller
- Instantiating controller 
Returns
booltrue if secure connection required
_sortedUnlocked() ¶ protected
_sortedUnlocked(array $data): stringGet the sorted unlocked string
Parameters
- 
                array$data
- Data array 
Returns
string_throwException() ¶ protected
_throwException(Cake\Controller\Exception\SecurityException|null $exception = null): voidCheck debug status and throw an Exception based on the existing one
Parameters
- 
                Cake\Controller\Exception\SecurityException|null$exception optional
- Additional debug info describing the cause 
Returns
voidThrows
Cake\Network\Exception\BadRequestException_unlocked() ¶ protected
_unlocked(array $data): stringGet the unlocked string
Parameters
- 
                array$data
- Data array 
Returns
string_validToken() ¶ protected
_validToken(Cake\Controller\Controller $controller): stringCheck if token is valid
Parameters
- 
                Cake\Controller\Controller$controller
- Instantiating controller 
Returns
stringfields token
Throws
Cake\Controller\Exception\SecurityException_validatePost() ¶ protected
_validatePost(Cake\Controller\Controller $controller): boolValidate submitted form
Parameters
- 
                Cake\Controller\Controller$controller
- Instantiating controller 
Returns
booltrue if submitted form is valid
Throws
Cake\Controller\Exception\AuthSecurityExceptionblackHole() ¶ public
blackHole(Cake\Controller\Controller $controller, string $error = '', Cake\Controller\Exception\SecurityException|null $exception = null): mixedBlack-hole an invalid request with a 400 error or custom callback. If SecurityComponent::$blackHoleCallback is specified, it will use this callback by executing the method indicated in $error
Parameters
- 
                Cake\Controller\Controller$controller
- Instantiating controller 
- 
                string$error optional
- Error method 
- 
                Cake\Controller\Exception\SecurityException|null$exception optional
- Additional debug info describing the cause 
Returns
mixedIf specified, controller blackHoleCallback's response, or no return otherwise
Throws
Cake\Network\Exception\BadRequestExceptionSee Also
Links
config() ¶ public
config(string|array|null $key = null, mixed|null $value = null, bool $merge = true): mixedUsage
Reading the whole config:
$this->config();Reading a specific value:
$this->config('key');Reading a nested value:
$this->config('some.nested.key');Setting a specific value:
$this->config('key', $value);Setting a nested value:
$this->config('some.nested.key', $value);Updating multiple config settings at the same time:
$this->config(['one' => 'value', 'another' => 'value']);Parameters
- 
                string|array|null$key optional
- The key to get/set, or a complete array of configs. 
- 
                mixed|null$value optional
- The value to set. 
- 
                bool$merge optional
- Whether to recursively merge or overwrite existing config, defaults to true. 
Returns
mixedConfig value being read, or the object itself on write operations.
Throws
Cake\Core\Exception\ExceptionWhen trying to set a key that is invalid.
configShallow() ¶ public
configShallow(string|array $key, mixed|null $value = null): $thisMerge provided config with existing config. Unlike config() which does
a recursive merge for nested keys, this method does a simple merge.
Setting a specific value:
$this->config('key', $value);Setting a nested value:
$this->config('some.nested.key', $value);Updating multiple config settings at the same time:
$this->config(['one' => 'value', 'another' => 'value']);Parameters
- 
                string|array$key
- The key to set, or a complete array of configs. 
- 
                mixed|null$value optional
- The value to set. 
Returns
$thisThe object itself.
generateToken() ¶ public
generateToken(Cake\Network\Request $request): boolManually add form tampering prevention token information into the provided request object.
Parameters
- 
                Cake\Network\Request$request
- The request object to add into. 
Returns
boolimplementedEvents() ¶ public
implementedEvents(): arrayEvents supported by this component.
Uses Conventions to map controller events to standard component callback method names. By defining one of the callback methods a component is assumed to be interested in the related event.
Override this method if you need to add non-conventional event listeners. Or if you want components to listen to non-standard events.
Returns
arrayinitialize() ¶ public
initialize(array $config): voidConstructor hook method.
Implement this method to avoid having to overwrite the constructor and call parent.
Parameters
- 
                array$config
- The configuration settings provided to this component. 
Returns
voidlog() ¶ public
log(mixed $msg, int|string $level = LogLevel::ERROR, string|array $context = []): boolConvenience method to write a message to Log. See Log::write() for more information on writing to logs.
Parameters
- 
                mixed$msg
- Log message. 
- 
                int|string$level optional
- Error level. 
- 
                string|array$context optional
- Additional log data relevant to this message. 
Returns
boolSuccess of log write.
requireAuth() ¶ public
requireAuth(string|array $actions): voidSets the actions that require whitelisted form submissions.
Adding actions with this method will enforce the restrictions set in SecurityComponent::$allowedControllers and SecurityComponent::$allowedActions.
Parameters
- 
                string|array$actions
- Actions list 
Returns
voidrequireSecure() ¶ public
requireSecure(string|array|null $actions = null): voidSets the actions that require a request that is SSL-secured, or empty for all actions
Parameters
- 
                string|array|null$actions optional
- Actions list 
Returns
voidstartup() ¶ public
startup(Cake\Event\Event $event): mixedComponent startup. All security checking happens here.
Parameters
- 
                Cake\Event\Event$event
- An Event instance 
Returns
mixedProperty Detail
$_configInitialized ¶ protected
Whether the config property has already been configured with defaults
Type
bool$_defaultConfig ¶ protected
Default config
- blackHoleCallback- The controller method that will be called if this request is black-hole'd.
- requireSecure- List of actions that require an SSL-secured connection.
- requireAuth- List of actions that require a valid authentication key. Deprecated as of 3.2.2
- allowedControllers- Controllers from which actions of the current controller are allowed to receive requests.
- allowedActions- Actions from which actions of the current controller are allowed to receive requests.
- unlockedFields- Form fields to exclude from POST validation. Fields can be unlocked either in the Component, or with FormHelper::unlockField(). Fields that have been unlocked are not required to be part of the POST and hidden unlocked fields do not have their values checked.
- unlockedActions- Actions to exclude from POST validation checks. Other checks like requireAuth(), requireSecure() etc. will still be applied.
- validatePost- Whether to validate POST data. Set to false to disable for data coming from 3rd party services, etc.
Type
array$_registry ¶ protected
Component registry class used to lazy load components.
Type
Cake\Controller\ComponentRegistry