Fr3nch13/CakePHP Utilities

SecurityComponent extends Component
in package

The Security Component creates an easy way to integrate tighter security in your application. It provides methods for these tasks:

Use instead, for form tampering protection or to enforce use of HTTPS (SSL) for requests.

  • Form tampering protection.
  • Requiring that SSL be used.
Tags
link
https://book.cakephp.org/4/en/controllers/components/security.html

Table of Contents

Constants

DEFAULT_EXCEPTION_MESSAGE  = 'The request has been black-holed'
Default message used for exceptions thrown

Properties

$_action  : string
Holds the current action of the controller
$_componentMap  : array<string, array<string|int, mixed>>
A component lookup table used to lazy load component objects.
$_config  : array<string, mixed>
Runtime config
$_configInitialized  : bool
Whether the config property has already been configured with defaults
$_defaultConfig  : array<string, mixed>
Default config
$_registry  : ComponentRegistry
Component registry class used to lazy load components.
$components  : array<string|int, mixed>
Other Components this component uses.

Methods

__construct()  : mixed
Constructor
__debugInfo()  : array<string, mixed>
Returns an array that can be used to describe the internal state of this object.
__get()  : Component|null
Magic method for lazy loading $components.
blackHole()  : mixed
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
configShallow()  : $this
Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
generateToken()  : ServerRequest
Manually add form tampering prevention token information into the provided request object.
getConfig()  : mixed
Returns the config.
getConfigOrFail()  : mixed
Returns the config for this specific key.
getController()  : Controller
Get the controller this component is bound to.
implementedEvents()  : array<string, mixed>
Events supported by this component.
initialize()  : void
Constructor hook method.
log()  : bool
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
requireSecure()  : void
Sets the actions that require a request that is SSL-secured, or empty for all actions
setConfig()  : $this
Sets the config.
startup()  : Response|null
Component startup. All security checking happens here.
_callback()  : mixed
Calls a controller callback method
_configDelete()  : void
Deletes a single config key.
_configRead()  : mixed
Reads a config key.
_configWrite()  : void
Writes a config key.
_debugCheckFields()  : array<string|int, string>
Iterates data array to check against expected
_debugExpectedFields()  : string|null
Generate debug message for the expected fields
_debugPostTokenNotMatching()  : string
Create a message for humans to understand why Security token is not matching
_fieldsList()  : array<string|int, mixed>
Return the fields list for the hash calculation
_hashParts()  : array<string|int, string>
Return hash parts for the Token generation
_matchExistingFields()  : array<string|int, string>
Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset
_secureRequired()  : void
Check if access requires secure connection
_sortedUnlocked()  : string
Get the sorted unlocked string
_throwException()  : void
Check debug status and throw an Exception based on the existing one
_unlocked()  : string
Get the unlocked string
_validatePost()  : void
Validate submitted form
_validToken()  : string
Check if token is valid

Constants

DEFAULT_EXCEPTION_MESSAGE

Default message used for exceptions thrown

public string DEFAULT_EXCEPTION_MESSAGE = 'The request has been black-holed'

Properties

$_action

Holds the current action of the controller

protected string $_action

$_componentMap

A component lookup table used to lazy load component objects.

protected array<string, array<string|int, mixed>> $_componentMap = []

$_configInitialized

Whether the config property has already been configured with defaults

protected bool $_configInitialized = false

$_defaultConfig

Default config

protected array<string, mixed> $_defaultConfig = ['blackHoleCallback' => null, 'requireSecure' => [], 'unlockedFields' => [], 'unlockedActions' => [], 'validatePost' => true]
  • 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.
  • 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 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.

$components

Other Components this component uses.

protected array<string|int, mixed> $components = []

Methods

__construct()

Constructor

public __construct(ComponentRegistry $registry[, array<string, mixed> $config = [] ]) : mixed
Parameters
$registry : ComponentRegistry

A component registry this component can use to lazy load its components.

$config : array<string, mixed> = []

Array of configuration settings.

__debugInfo()

Returns an array that can be used to describe the internal state of this object.

public __debugInfo() : array<string, mixed>
Return values
array<string, mixed>

__get()

Magic method for lazy loading $components.

public __get(string $name) : Component|null
Parameters
$name : string

Name of component to get.

Return values
Component|null

A Component object or null.

blackHole()

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

public blackHole(Controller $controller[, string $error = '' ][, SecurityException|null $exception = null ]) : mixed
Parameters
$controller : Controller

Instantiating controller

$error : string = ''

Error method

$exception : SecurityException|null = null

Additional debug info describing the cause

Tags
see
SecurityComponent::$blackHoleCallback
link
https://book.cakephp.org/4/en/controllers/components/security.html#handling-blackhole-callbacks
throws
BadRequestException
Return values
mixed

If specified, controller blackHoleCallback's response, or no return otherwise

configShallow()

Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.

public configShallow(array<string, mixed>|string $key[, mixed|null $value = null ]) : $this

Setting a specific value:

$this->configShallow('key', $value);

Setting a nested value:

$this->configShallow('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->configShallow(['one' => 'value', 'another' => 'value']);
Parameters
$key : array<string, mixed>|string

The key to set, or a complete array of configs.

$value : mixed|null = null

The value to set.

Return values
$this

getConfig()

Returns the config.

public getConfig([string|null $key = null ][, mixed $default = null ]) : mixed

Usage

Reading the whole config:

$this->getConfig();

Reading a specific value:

$this->getConfig('key');

Reading a nested value:

$this->getConfig('some.nested.key');

Reading with default value:

$this->getConfig('some-key', 'default-value');
Parameters
$key : string|null = null

The key to get or null for the whole config.

$default : mixed = null

The return value when the key does not exist.

Return values
mixed

Configuration data at the named key or null if the key does not exist.

getConfigOrFail()

Returns the config for this specific key.

public getConfigOrFail(string $key) : mixed

The config value for this key must exist, it can never be null.

Parameters
$key : string

The key to get.

Tags
throws
InvalidArgumentException
Return values
mixed

Configuration data at the named key

getController()

Get the controller this component is bound to.

public getController() : Controller
Return values
Controller

The bound controller.

implementedEvents()

Events supported by this component.

public implementedEvents() : array<string, mixed>
Return values
array<string, mixed>

initialize()

Constructor hook method.

public initialize(array<string, mixed> $config) : void

Implement this method to avoid having to overwrite the constructor and call parent.

Parameters
$config : array<string, mixed>

The configuration settings provided to this component.

log()

Convenience method to write a message to Log. See Log::write() for more information on writing to logs.

public log(string $message[, string|int $level = LogLevel::ERROR ][, array<string|int, mixed>|string $context = [] ]) : bool
Parameters
$message : string

Log message.

$level : string|int = LogLevel::ERROR

Error level.

$context : array<string|int, mixed>|string = []

Additional log data relevant to this message.

Return values
bool

Success of log write.

requireSecure()

Sets the actions that require a request that is SSL-secured, or empty for all actions

public requireSecure([array<string|int, string>|string|null $actions = null ]) : void
Parameters
$actions : array<string|int, string>|string|null = null

Actions list

setConfig()

Sets the config.

public setConfig(array<string, mixed>|string $key[, mixed|null $value = null ][, bool $merge = true ]) : $this

Usage

Setting a specific value:

$this->setConfig('key', $value);

Setting a nested value:

$this->setConfig('some.nested.key', $value);

Updating multiple config settings at the same time:

$this->setConfig(['one' => 'value', 'another' => 'value']);
Parameters
$key : array<string, mixed>|string

The key to set, or a complete array of configs.

$value : mixed|null = null

The value to set.

$merge : bool = true

Whether to recursively merge or overwrite existing config, defaults to true.

Tags
throws
CakeException

When trying to set a key that is invalid.

Return values
$this

_callback()

Calls a controller callback method

protected _callback(Controller $controller, string $method[, array<string|int, mixed> $params = [] ]) : mixed
Parameters
$controller : Controller

Instantiating controller

$method : string

Method to execute

$params : array<string|int, mixed> = []

Parameters to send to method

Tags
throws
BadRequestException

When a the blackholeCallback is not callable.

Return values
mixed

Controller callback method's response

_configDelete()

Deletes a single config key.

protected _configDelete(string $key) : void
Parameters
$key : string

Key to delete.

Tags
throws
CakeException

if attempting to clobber existing config

_configRead()

Reads a config key.

protected _configRead(string|null $key) : mixed
Parameters
$key : string|null

Key to read.

_configWrite()

Writes a config key.

protected _configWrite(array<string, mixed>|string $key, mixed $value[, string|bool $merge = false ]) : void
Parameters
$key : array<string, mixed>|string

Key to write to.

$value : mixed

Value to write.

$merge : string|bool = false

True to merge recursively, 'shallow' for simple merge, false to overwrite, defaults to false.

Tags
throws
CakeException

if attempting to clobber existing config

_debugCheckFields()

Iterates data array to check against expected

protected _debugCheckFields(array<string|int, mixed> $dataFields[, array<string|int, mixed> $expectedFields = [] ][, string $intKeyMessage = '' ][, string $stringKeyMessage = '' ][, string $missingMessage = '' ]) : array<string|int, string>
Parameters
$dataFields : array<string|int, mixed>

Fields array, containing the POST data fields

$expectedFields : array<string|int, mixed> = []

Fields array, containing the expected fields we should have in POST

$intKeyMessage : string = ''

Message string if unexpected found in data fields indexed by int (not protected)

$stringKeyMessage : string = ''

Message string if tampered found in data fields indexed by string (protected).

$missingMessage : string = ''

Message string if missing field

Return values
array<string|int, string>

Messages

_debugExpectedFields()

Generate debug message for the expected fields

protected _debugExpectedFields([array<string|int, mixed> $expectedFields = [] ][, string $missingMessage = '' ]) : string|null
Parameters
$expectedFields : array<string|int, mixed> = []

Expected fields

$missingMessage : string = ''

Message template

Return values
string|null

Error message about expected fields

_debugPostTokenNotMatching()

Create a message for humans to understand why Security token is not matching

protected _debugPostTokenNotMatching(Controller $controller, array<string|int, string> $hashParts) : string
Parameters
$controller : Controller

Instantiating controller

$hashParts : array<string|int, string>

Elements used to generate the Token hash

Return values
string

Message explaining why the tokens are not matching

_fieldsList()

Return the fields list for the hash calculation

protected _fieldsList(array<string|int, mixed> $check) : array<string|int, mixed>
Parameters
$check : array<string|int, mixed>

Data array

Return values
array<string|int, mixed>

_hashParts()

Return hash parts for the Token generation

protected _hashParts(Controller $controller) : array<string|int, string>
Parameters
$controller : Controller

Instantiating controller

Return values
array<string|int, string>

_matchExistingFields()

Generate array of messages for the existing fields in POST data, matching dataFields in $expectedFields will be unset

protected _matchExistingFields(array<string|int, mixed> $dataFields, array<string|int, mixed> &$expectedFields, string $intKeyMessage, string $stringKeyMessage) : array<string|int, string>
Parameters
$dataFields : array<string|int, mixed>

Fields array, containing the POST data fields

$expectedFields : array<string|int, mixed>

Fields array, containing the expected fields we should have in POST

$intKeyMessage : string

Message string if unexpected found in data fields indexed by int (not protected)

$stringKeyMessage : string

Message string if tampered found in data fields indexed by string (protected)

Return values
array<string|int, string>

Error messages

_sortedUnlocked()

Get the sorted unlocked string

protected _sortedUnlocked(array<string|int, mixed> $data) : string
Parameters
$data : array<string|int, mixed>

Data array

Return values
string

_unlocked()

Get the unlocked string

protected _unlocked(array<string|int, mixed> $data) : string
Parameters
$data : array<string|int, mixed>

Data array

Return values
string

        
On this page

Search results