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.
- CSRF protection.
- Form tampering protection
- Requiring that SSL be used.
- Limiting cross controller communication.
- CakeObject
- Component
- SecurityComponent
Link: https://book.cakephp.org/2.0/en/core-libraries/components/security-component.html
Copyright: Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
License: MIT License
Location: Cake/Controller/Component/SecurityComponent.php
Constants summary
-
string
DEFAULT_EXCEPTION_MESSAGE
¶'The request has been black-holed'
Properties summary
-
$_action
protectedstring
Holds the current action of the controller -
$allowedActions
publicarray
Actions from which actions of the current controller are allowed to receive requests.
-
$allowedControllers
publicarray
Controllers from which actions of the current controller are allowed to receive requests.
-
$blackHoleCallback
publicstring
The controller method that will be called if this request is black-hole'd -
$components
publicarray
Other components used by the Security component -
$csrfCheck
publicboolean
Whether to use CSRF protected forms. Set to false to disable CSRF protection on forms. -
$csrfExpires
publicstring
The duration from when a CSRF token is created that it will expire on. Each form/page request will generate a new token that can only be submitted once unless it expires. Can be any value compatible with strtotime()
-
$csrfLimit
publicinteger
Control the number of tokens a user can keep open. This is most useful with one-time use tokens. Since new tokens are created on each request, having a hard limit on the number of open tokens can be useful in controlling the size of the session file.
-
$csrfUseOnce
publicboolean
Controls whether or not CSRF tokens are use and burn. Set to false to not generate new tokens on each request. One token will be reused until it expires. This reduces the chances of users getting invalid requests because of token consumption. It has the side effect of making CSRF less secure, as tokens are reusable.
-
$disabledFields
publicarray
Deprecated property, superseded by unlockedFields. -
$request
publicRequest object -
$requireAuth
publicarray
List of actions that require a valid authentication key -
$requireDelete
publicarray
List of controller actions for which a DELETE request is required -
$requireGet
publicarray
List of controller actions for which a GET request is required -
$requirePost
publicarray
List of controller actions for which a POST request is required -
$requirePut
publicarray
List of controller actions for which a PUT request is required -
$requireSecure
publicarray
List of actions that require an SSL-secured connection -
$unlockedActions
publicarray
Actions to exclude from CSRF and POST validation checks. Other checks like requireAuth(), requireSecure(), requirePost(), requireGet() etc. will still be applied.
-
$unlockedFields
publicarray
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.
-
$validatePost
publicboolean
Whether to validate POST data. Set to false to disable for data coming from 3rd party services, etc.
Inherited Properties
Method Summary
-
_authRequired() protected deprecated
Check if authentication is required -
_callback() protected
Calls a controller callback method -
_debugCheckFields() protected
Iterates data array to check against expected -
_debugExpectedFields() protected
Generate debug message for the expected fields -
_debugPostTokenNotMatching() protected
Create a message for humans to understand why Security token is not matching -
_expireTokens() protected
Expire CSRF nonces and remove them from the valid tokens. Uses a simple timeout to expire the tokens.
-
_fieldsList() protected
Return the fields list for the hash calculation -
_hashParts() protected
Return hash parts for the Token generation -
_matchExistingFields() protected
Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset
-
_methodsRequired() protected
Check if HTTP methods are required -
_requireMethod() protected
Sets the actions that require a $method HTTP request, or empty for all actions -
_secureRequired() protected
Check if access requires secure connection -
_sortedUnlocked() protected
Get the sorted unlocked string -
_throwException() protected
Check debug status and throw an Exception based on the existing one -
_unlocked() protected
Get the unlocked string -
_validToken() protected
Check if token is valid -
_validateCsrf() protected
Validate that the controller has a CSRF token in the POST data and that the token is legit/not expired. If the token is valid it will be removed from the list of valid tokens.
-
_validatePost() protected
Validate submitted form -
blackHole() public
Black-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
-
generateToken() public
Manually add CSRF token information into the provided request object. -
requireAuth() public
Sets the actions that require whitelisted form submissions. -
requireDelete() public deprecated
Sets the actions that require a DELETE request, or empty for all actions -
requireGet() public deprecated
Sets the actions that require a GET request, or empty for all actions -
requirePost() public deprecated
Sets the actions that require a POST request, or empty for all actions -
requirePut() public deprecated
Sets the actions that require a PUT request, or empty for all actions -
requireSecure() public
Sets the actions that require a request that is SSL-secured, or empty for all actions -
startup() public
Component startup. All security checking happens here.
Method Detail
_authRequired() protected deprecated ¶
_authRequired( Controller
$controller )
Check if authentication is required
Deprecated
Parameters
-
Controller
$controller - Instantiating controller
Returns
True if authentication required
Throws
_callback() protected ¶
_callback( Controller
$controller , string $method , array $params = array() )
Calls a controller callback method
Parameters
-
Controller
$controller - Controller to run callback on
- string $method
- Method to execute
- array $params optional array()
- Parameters to send to method
Returns
Controller callback method's response
Throws
_debugCheckFields() protected ¶
_debugCheckFields( array $dataFields , array $expectedFields = array() , string $intKeyMessage = '' , string $stringKeyMessage = '' , string $missingMessage = '' )
Iterates data array to check against expected
Parameters
- array $dataFields
- Fields array, containing the POST data fields
- array $expectedFields optional array()
- 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
Messages
_debugExpectedFields() protected ¶
_debugExpectedFields( array $expectedFields = array() , string $missingMessage = '' )
Generate debug message for the expected fields
Parameters
- array $expectedFields optional array()
- Expected fields
- string $missingMessage optional ''
- Message template
Returns
Error message about expected fields
_debugPostTokenNotMatching() protected ¶
_debugPostTokenNotMatching( Controller
$controller , array $hashParts )
Create a message for humans to understand why Security token is not matching
Parameters
-
Controller
$controller - Instantiating controller
- array $hashParts
- Elements used to generate the Token hash
Returns
Message explaining why the tokens are not matching
_expireTokens() protected ¶
_expireTokens( array $tokens )
Expire CSRF nonces and remove them from the valid tokens. Uses a simple timeout to expire the tokens.
Parameters
- array $tokens
- An array of nonce => expires.
Returns
An array of nonce => expires.
_fieldsList() protected ¶
_fieldsList( array $check )
Return the fields list for the hash calculation
Parameters
- array $check
- Data array
Returns
_hashParts() protected ¶
_hashParts( Controller
$controller )
Return hash parts for the Token generation
Parameters
-
Controller
$controller - Instantiating controller
Returns
_matchExistingFields() protected ¶
_matchExistingFields( array $dataFields , array $expectedFields , string $intKeyMessage , string $stringKeyMessage )
Generate 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
- $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
Error messages
_methodsRequired() protected ¶
_methodsRequired( Controller
$controller )
Check if HTTP methods are required
Parameters
-
Controller
$controller - Instantiating controller
Returns
True if $method is required
Throws
_requireMethod() protected ¶
_requireMethod( string $method , array $actions = array() )
Sets 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 array()
- Controller actions to set the required HTTP method to.
_secureRequired() protected ¶
_secureRequired( Controller
$controller )
Check if access requires secure connection
Parameters
-
Controller
$controller - Instantiating controller
Returns
True if secure connection required
Throws
_sortedUnlocked() protected ¶
_sortedUnlocked( array $data )
Get the sorted unlocked string
Parameters
- array $data
- Data array
Returns
_throwException() protected ¶
_throwException( SecurityException
|null $exception = null )
Check debug status and throw an Exception based on the existing one
Parameters
-
SecurityException
|null $exception optional null - Additional debug info describing the cause
Throws
_unlocked() protected ¶
_unlocked( array $data )
Get the unlocked string
Parameters
- array $data
- Data array
Returns
_validToken() protected ¶
_validToken( Controller
$controller )
Check if token is valid
Parameters
-
Controller
$controller - Instantiating controller
Returns
fields token
Throws
_validateCsrf() protected ¶
_validateCsrf( Controller
$controller )
Validate that the controller has a CSRF token in the POST data and that the token is legit/not expired. If the token is valid it will be removed from the list of valid tokens.
Parameters
-
Controller
$controller - A controller to check
Returns
Valid csrf token.
Throws
_validatePost() protected ¶
_validatePost( Controller
$controller )
Validate submitted form
Parameters
-
Controller
$controller - Instantiating controller
Returns
true if submitted form is valid
Throws
blackHole() public ¶
blackHole( Controller
$controller , string $error = '' , SecurityException
$exception = null )
Black-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
-
Controller
$controller - Instantiating controller
- string $error optional ''
- Error method
-
SecurityException
$exception optional null - Additional debug info describing the cause
Returns
If specified, controller blackHoleCallback's response, or no return otherwise
Throws
See
Link
generateToken() public ¶
generateToken( CakeRequest
$request )
Manually add CSRF token information into the provided request object.
Parameters
-
CakeRequest
$request - The request object to add into.
Returns
requireAuth() public ¶
requireAuth( )
Sets the actions that require whitelisted form submissions.
Adding actions with this method will enforce the restrictions set in SecurityComponent::$allowedControllers and SecurityComponent::$allowedActions.
Link
requireDelete() public deprecated ¶
requireDelete( )
Sets the actions that require a DELETE request, or empty for all actions
Deprecated
requireGet() public deprecated ¶
requireGet( )
Sets the actions that require a GET request, or empty for all actions
Deprecated
requirePost() public deprecated ¶
requirePost( )
Sets the actions that require a POST request, or empty for all actions
Deprecated
Link
requirePut() public deprecated ¶
requirePut( )
Sets the actions that require a PUT request, or empty for all actions
Deprecated
requireSecure() public ¶
requireSecure( )
Sets the actions that require a request that is SSL-secured, or empty for all actions
Link
startup() public ¶
startup( Controller
$controller )
Component startup. All security checking happens here.
Parameters
-
Controller
$controller - Instantiating controller
Throws
Overrides
Methods inherited from Component
__construct() public ¶
__construct( ComponentCollection
$collection , array $settings = array() )
Constructor
Parameters
-
ComponentCollection
$collection - A ComponentCollection this component can use to lazy load its components
- array $settings optional array()
- Array of configuration settings.
Overrides
__get() public ¶
__get( string $name )
Magic method for lazy loading $components.
Parameters
- string $name
- Name of component to get.
Returns
A Component object or null.
beforeRedirect() public ¶
beforeRedirect( Controller
$controller , string|array $url , integer $status = null , boolean $exit = true )
Called before Controller::redirect(). Allows you to replace the URL that will be redirected to with a new URL. The return of this method can either be an array or a string.
If the return is an array and contains a 'url' key. You may also supply the following:
status
The status code for the redirectexit
Whether or not the redirect should exit.
If your response is a string or an array that does not contain a 'url' key it will be used as the new URL to redirect to.
Parameters
-
Controller
$controller - Controller with components to beforeRedirect
- string|array $url
- Either the string or URL array that is being redirected to.
- integer $status optional null
- The status code of the redirect
- boolean $exit optional true
- Will the script exit.
Returns
Either an array or null.
Link
beforeRender() public ¶
beforeRender( Controller
$controller )
Called before the Controller::beforeRender(), and before the view class is loaded, and before Controller::render()
Parameters
-
Controller
$controller - Controller with components to beforeRender
Link
initialize() public ¶
initialize( Controller
$controller )
Called before the Controller::beforeFilter().
Parameters
-
Controller
$controller - Controller with components to initialize
Link
shutdown() public ¶
shutdown( Controller
$controller )
Called after Controller::render() and before the output is printed to the browser.
Parameters
-
Controller
$controller - Controller with components to shutdown
Link
Methods inherited from CakeObject
_mergeVars() protected ¶
_mergeVars( array $properties , string $class , boolean $normalize = true )
Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'
This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.
Parameters
- array $properties
- The name of the properties to merge.
- string $class
- The class to merge the property with.
- boolean $normalize optional true
- Set to true to run the properties through Hash::normalize() before merging.
_set() protected ¶
_set( array $properties = array() )
Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.
Parameters
- array $properties optional array()
- An associative array containing properties and corresponding values.
_stop() protected ¶
_stop( integer|string $status = 0 )
Stop execution of the current script. Wraps exit() making testing easier.
Parameters
- integer|string $status optional 0
- see http://php.net/exit for values
dispatchMethod() public ¶
dispatchMethod( string $method , array $params = array() )
Calls a method on this object with the given parameters. Provides an OO wrapper
for call_user_func_array
Parameters
- string $method
- Name of the method to call
- array $params optional array()
- Parameter list to use when calling $method
Returns
Returns the result of the method call
log() public ¶
log( mixed $msg , integer $type = LOG_ERR , null|string|array $scope = null )
Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.
Parameters
- mixed $msg
- Log message
- integer $type optional LOG_ERR
- Error type constant. Defined in app/Config/core.php.
- null|string|array $scope optional null
The scope(s) a log message is being created in. See CakeLog::config() for more information on logging scopes.
Returns
Success of log write
requestAction() public ¶
requestAction( string|array $url , array $extra = array() )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()
Passing POST and GET data
POST and GET data can be simulated in requestAction. Use $extra['url']
for
GET data. The $extra['data']
parameter allows POST data simulation.
Parameters
- string|array $url
String or array-based URL. Unlike other URL arrays in CakePHP, this URL will not automatically handle passed and named arguments in the $url parameter.
- array $extra optional array()
if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.
Returns
Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.
toString() public ¶
toString( )
CakeObject-to-string conversion. Each class can override this method as necessary.
Returns
The name of this class
Properties detail
$allowedActions ¶
Actions from which actions of the current controller are allowed to receive requests.
See
array()
$allowedControllers ¶
Controllers from which actions of the current controller are allowed to receive requests.
See
array()
$blackHoleCallback ¶
The controller method that will be called if this request is black-hole'd
null
$csrfCheck ¶
Whether to use CSRF protected forms. Set to false to disable CSRF protection on forms.
See
SecurityComponent::$csrfExpires
true
$csrfExpires ¶
The duration from when a CSRF token is created that it will expire on. Each form/page request will generate a new token that can only be submitted once unless it expires. Can be any value compatible with strtotime()
'+30 minutes'
$csrfLimit ¶
Control the number of tokens a user can keep open. This is most useful with one-time use tokens. Since new tokens are created on each request, having a hard limit on the number of open tokens can be useful in controlling the size of the session file.
When tokens are evicted, the oldest ones will be removed, as they are the most likely to be dead/expired.
100
$csrfUseOnce ¶
Controls whether or not CSRF tokens are use and burn. Set to false to not generate new tokens on each request. One token will be reused until it expires. This reduces the chances of users getting invalid requests because of token consumption. It has the side effect of making CSRF less secure, as tokens are reusable.
true
$disabledFields ¶
Deprecated property, superseded by unlockedFields.
Deprecated
See
array()
$requireAuth ¶
List of actions that require a valid authentication key
See
Deprecated
array()
$requireDelete ¶
List of controller actions for which a DELETE request is required
Deprecated
See
array()
$requireGet ¶
List of controller actions for which a GET request is required
Deprecated
See
array()
$requirePost ¶
List of controller actions for which a POST request is required
Deprecated
See
array()
$requirePut ¶
List of controller actions for which a PUT request is required
Deprecated
See
array()
$requireSecure ¶
List of actions that require an SSL-secured connection
See
array()
$unlockedActions ¶
Actions to exclude from CSRF and POST validation checks. Other checks like requireAuth(), requireSecure(), requirePost(), requireGet() etc. will still be applied.
array()
$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.
array()
$validatePost ¶
Whether to validate POST data. Set to false to disable for data coming from 3rd party services, etc.
true