AuthComponent
extends Component
in package
implements
EventDispatcherInterface
uses
EventDispatcherTrait
Authentication control component class.
Use the cakephp/authentication and cakephp/authorization plugins instead.
Binds access control with user authentication and session management.
Tags
Table of Contents
Interfaces
- EventDispatcherInterface
- Objects implementing this interface can emit events.
Constants
- ALL = 'all'
- Constant for 'all'
- QUERY_STRING_REDIRECT = 'redirect'
- The query string key used for remembering the referred page when getting redirected to login.
Properties
- $allowedActions : array<string|int, string>
- Controller actions for which user validation is not required.
- $Flash : FlashComponent
- $RequestHandler : RequestHandlerComponent
- $_authenticateObjects : array<string|int, BaseAuthenticate>
- Objects that will be used for authentication checks.
- $_authenticationProvider : BaseAuthenticate|null
- The instance of the Authenticate provider that was used for successfully logging in the current user after calling `login()` in the same request
- $_authorizationProvider : BaseAuthorize|null
- The instance of the Authorize provider that was used to grant access to the current user to the URL they are requesting.
- $_authorizeObjects : array<string|int, BaseAuthorize>
- Objects that will be used for authorization checks.
- $_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
- $_eventClass : string
- Default class name for new event objects.
- $_eventManager : EventManagerInterface|null
- Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
- $_registry : ComponentRegistry
- Component registry class used to lazy load components.
- $_storage : StorageInterface|null
- Storage object.
- $components : array<string|int, mixed>
- Other components utilized by AuthComponent
Methods
- __construct() : mixed
- Constructor
- __debugInfo() : array<string, mixed>
- Returns an array that can be used to describe the internal state of this object.
- __get() : mixed
- Magic accessor for backward compatibility for property `$sessionKey`.
- __set() : void
- Magic setter for backward compatibility for property `$sessionKey`.
- allow() : void
- Takes a list of actions in the current controller for which authentication is not required, or no parameters to allow all actions.
- authCheck() : Response|null
- Main execution method, handles initial authentication check and redirection of invalid users.
- authenticationProvider() : BaseAuthenticate|null
- If login was called during this request and the user was successfully authenticated, this function will return the instance of the authentication object that was used for logging the user in.
- authorizationProvider() : BaseAuthorize|null
- If there was any authorization processing for the current request, this function will return the instance of the Authorization object that granted access to the user to the current address.
- configShallow() : $this
- Merge provided config with existing config. Unlike `config()` which does a recursive merge for nested keys, this method does a simple merge.
- constructAuthenticate() : array<string, object>|null
- Loads the configured authentication objects.
- constructAuthorize() : array<string|int, mixed>|null
- Loads the authorization objects configured.
- deny() : void
- Removes items from the list of allowed/no authentication required actions.
- dispatchEvent() : EventInterface
- Wrapper for creating and dispatching events.
- flash() : void
- Set a flash message. Uses the Flash component with values from `flash` config.
- getAuthenticate() : BaseAuthenticate|null
- Getter for authenticate objects. Will return a particular authenticate object.
- getAuthorize() : BaseAuthorize|null
- Getter for authorize objects. Will return a particular authorize 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.
- getEventManager() : EventManagerInterface
- Returns the Cake\Event\EventManager manager instance for this object.
- identify() : array<string|int, mixed>|false
- Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
- implementedEvents() : array<string, mixed>
- Events supported by this component.
- initialize() : void
- Initialize properties.
- isAuthorized() : bool
- Check if the provided user is authorized for the request.
- log() : bool
- Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
- logout() : string
- Log a user out.
- redirectUrl() : string
- Get the URL a user should be redirected to upon login.
- setConfig() : $this
- Sets the config.
- setEventManager() : $this
- Returns the Cake\Event\EventManagerInterface instance for this object.
- setUser() : void
- Set provided user info to storage as logged in user.
- startup() : Response|null
- Callback for Controller.startup event.
- storage() : StorageInterface|null
- Get/set user record storage object.
- user() : mixed|null
- Get the current user from storage.
- _configDelete() : void
- Deletes a single config key.
- _configRead() : mixed
- Reads a config key.
- _configWrite() : void
- Writes a config key.
- _getUrlToRedirectBackTo() : string
- Returns the URL to redirect back to or / if not possible.
- _getUser() : bool
- Similar to AuthComponent::user() except if user is not found in configured storage, connected authentication objects will have their getUser() methods called.
- _isAllowed() : bool
- Checks whether current action is accessible without authentication.
- _isLoginAction() : bool
- Normalizes config `loginAction` and checks if current request URL is same as login action.
- _loginActionRedirectUrl() : array<string|int, mixed>|string
- Returns the URL of the login action to redirect to.
- _setDefaults() : void
- Sets defaults for configs.
- _unauthenticated() : Response|null
- Handles unauthenticated access attempt. First the `unauthenticated()` method of the last authenticator in the chain will be called. The authenticator can handle sending response or redirection as appropriate and return `true` to indicate no further action is necessary. If authenticator returns null this method redirects user to login action.
- _unauthorized() : Response|null
- Handle unauthorized access attempt
Constants
ALL
Constant for 'all'
public
string
ALL
= 'all'
QUERY_STRING_REDIRECT
The query string key used for remembering the referred page when getting redirected to login.
public
string
QUERY_STRING_REDIRECT
= 'redirect'
Properties
$allowedActions
Controller actions for which user validation is not required.
public
array<string|int, string>
$allowedActions
= []
Tags
$Flash
public
FlashComponent
$Flash
$RequestHandler
public
RequestHandlerComponent
$RequestHandler
$_authenticateObjects
Objects that will be used for authentication checks.
protected
array<string|int, BaseAuthenticate>
$_authenticateObjects
= []
$_authenticationProvider
The instance of the Authenticate provider that was used for successfully logging in the current user after calling `login()` in the same request
protected
BaseAuthenticate|null
$_authenticationProvider
$_authorizationProvider
The instance of the Authorize provider that was used to grant access to the current user to the URL they are requesting.
protected
BaseAuthorize|null
$_authorizationProvider
$_authorizeObjects
Objects that will be used for authorization checks.
protected
array<string|int, BaseAuthorize>
$_authorizeObjects
= []
$_componentMap
A component lookup table used to lazy load component objects.
protected
array<string, array<string|int, mixed>>
$_componentMap
= []
$_config
Runtime config
protected
array<string, mixed>
$_config
= []
$_configInitialized
Whether the config property has already been configured with defaults
protected
bool
$_configInitialized
= false
$_defaultConfig
Default config
protected
array<string, mixed>
$_defaultConfig
= ['authenticate' => null, 'authorize' => null, 'flash' => null, 'loginAction' => null, 'loginRedirect' => null, 'logoutRedirect' => null, 'authError' => null, 'unauthorizedRedirect' => true, 'storage' => 'Session', 'checkAuthIn' => 'Controller.startup']
-
authenticate
- An array of authentication objects to use for authenticating users. You can configure multiple adapters and they will be checked sequentially when users are identified.$this->Auth->setConfig('authenticate', [ 'Form' => [ 'userModel' => 'Users.Users' ] ]);
Using the class name without 'Authenticate' as the key, you can pass in an array of config for each authentication object. Additionally, you can define config that should be set to all authentications objects using the 'all' key:
$this->Auth->setConfig('authenticate', [ AuthComponent::ALL => [ 'userModel' => 'Users.Users', 'scope' => ['Users.active' => 1] ], 'Form', 'Basic' ]);
-
authorize
- An array of authorization objects to use for authorizing users. You can configure multiple adapters and they will be checked sequentially when authorization checks are done.$this->Auth->setConfig('authorize', [ 'Crud' => [ 'actionPath' => 'controllers/' ] ]);
Using the class name without 'Authorize' as the key, you can pass in an array of config for each authorization object. Additionally you can define config that should be set to all authorization objects using the AuthComponent::ALL key:
$this->Auth->setConfig('authorize', [ AuthComponent::ALL => [ 'actionPath' => 'controllers/' ], 'Crud', 'CustomAuth' ]);
-
flash
- Settings to use when Auth needs to do a flash message with FlashComponent::set(). Available keys are:-
key
- The message domain to use for flashes generated by this component, defaults to 'auth'. -
element
- Flash element to use, defaults to 'default'. -
params
- The array of additional params to use, defaults to ['class' => 'error']
-
-
loginAction
- A URL (defined as a string or array) to the controller action that handles logins. Defaults to/users/login
. -
loginRedirect
- Normally, if a user is redirected to theloginAction
page, the location they were redirected from will be stored in the session so that they can be redirected back after a successful login. If this session value is not set, redirectUrl() method will return the URL specified inloginRedirect
. -
logoutRedirect
- The default action to redirect to after the user is logged out. While AuthComponent does not handle post-logout redirection, a redirect URL will be returned fromAuthComponent::logout()
. Defaults tologinAction
. -
authError
- Error to display when user attempts to access an object or action to which they do not have access. -
unauthorizedRedirect
- Controls handling of unauthorized access.- For default value
true
unauthorized user is redirected to the referrer URL or$loginRedirect
or '/'. - If set to a string or array the value is used as a URL to redirect to.
- If set to false a
ForbiddenException
exception is thrown instead of redirecting.
- For default value
-
storage
- Storage class to use for persisting user record. When using stateless authenticator you should set this to 'Memory'. Defaults to 'Session'. -
checkAuthIn
- Name of event for which initial auth checks should be done. Defaults to 'Controller.startup'. You can set it to 'Controller.initialize' if you want the check to be done before controller's beforeFilter() is run.
$_eventClass
Default class name for new event objects.
protected
string
$_eventClass
= \Cake\Event\Event::class
$_eventManager
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
protected
EventManagerInterface|null
$_eventManager
$_registry
Component registry class used to lazy load components.
protected
ComponentRegistry
$_registry
$_storage
Storage object.
protected
StorageInterface|null
$_storage
$components
Other components utilized by AuthComponent
protected
array<string|int, mixed>
$components
= ['RequestHandler', 'Flash']
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 accessor for backward compatibility for property `$sessionKey`.
public
__get(string $name) : mixed
Parameters
- $name : string
-
Property name
__set()
Magic setter for backward compatibility for property `$sessionKey`.
public
__set(string $name, mixed $value) : void
Parameters
- $name : string
-
Property name.
- $value : mixed
-
Value to set.
allow()
Takes a list of actions in the current controller for which authentication is not required, or no parameters to allow all actions.
public
allow([array<string|int, string>|string|null $actions = null ]) : void
You can use allow with either an array or a simple string.
$this->Auth->allow('view');
$this->Auth->allow(['edit', 'add']);
or to allow all actions
$this->Auth->allow();
Parameters
- $actions : array<string|int, string>|string|null = null
-
Controller action name or array of actions
Tags
authCheck()
Main execution method, handles initial authentication check and redirection of invalid users.
public
authCheck(EventInterface $event) : Response|null
The auth check is done when event name is same as the one configured in
checkAuthIn
config.
Parameters
- $event : EventInterface
-
Event instance.
Tags
Return values
Response|nullauthenticationProvider()
If login was called during this request and the user was successfully authenticated, this function will return the instance of the authentication object that was used for logging the user in.
public
authenticationProvider() : BaseAuthenticate|null
Return values
BaseAuthenticate|nullauthorizationProvider()
If there was any authorization processing for the current request, this function will return the instance of the Authorization object that granted access to the user to the current address.
public
authorizationProvider() : BaseAuthorize|null
Return values
BaseAuthorize|nullconfigShallow()
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
$thisconstructAuthenticate()
Loads the configured authentication objects.
public
constructAuthenticate() : array<string, object>|null
Tags
Return values
array<string, object>|null —The loaded authorization objects, or null on empty authenticate value.
constructAuthorize()
Loads the authorization objects configured.
public
constructAuthorize() : array<string|int, mixed>|null
Tags
Return values
array<string|int, mixed>|null —The loaded authorization objects, or null when authorize is empty.
deny()
Removes items from the list of allowed/no authentication required actions.
public
deny([array<string|int, string>|string|null $actions = null ]) : void
You can use deny with either an array or a simple string.
$this->Auth->deny('view');
$this->Auth->deny(['edit', 'add']);
or
$this->Auth->deny();
to remove all items from the allowed list
Parameters
- $actions : array<string|int, string>|string|null = null
-
Controller action name or array of actions
Tags
dispatchEvent()
Wrapper for creating and dispatching events.
public
dispatchEvent(string $name[, array<string|int, mixed>|null $data = null ][, object|null $subject = null ]) : EventInterface
Returns a dispatched event.
Parameters
- $name : string
-
Name of the event.
- $data : array<string|int, mixed>|null = null
-
Any value you wish to be transported with this event to it can be read by listeners.
- $subject : object|null = null
-
The object that this event applies to ($this by default).
Return values
EventInterfaceflash()
Set a flash message. Uses the Flash component with values from `flash` config.
public
flash(string|false $message) : void
Parameters
- $message : string|false
-
The message to set. False to skip.
getAuthenticate()
Getter for authenticate objects. Will return a particular authenticate object.
public
getAuthenticate(string $alias) : BaseAuthenticate|null
Parameters
- $alias : string
-
Alias for the authenticate object
Return values
BaseAuthenticate|nullgetAuthorize()
Getter for authorize objects. Will return a particular authorize object.
public
getAuthorize(string $alias) : BaseAuthorize|null
Parameters
- $alias : string
-
Alias for the authorize object
Return values
BaseAuthorize|nullgetConfig()
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
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.
getEventManager()
Returns the Cake\Event\EventManager manager instance for this object.
public
getEventManager() : EventManagerInterface
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
Return values
EventManagerInterfaceidentify()
Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
public
identify() : array<string|int, mixed>|false
Triggers Auth.afterIdentify
event which the authenticate classes can listen
to.
Return values
array<string|int, mixed>|false —User record data, or false, if the user could not be identified.
implementedEvents()
Events supported by this component.
public
implementedEvents() : array<string, mixed>
Return values
array<string, mixed>initialize()
Initialize properties.
public
initialize(array<string, mixed> $config) : void
Parameters
- $config : array<string, mixed>
-
The config data.
isAuthorized()
Check if the provided user is authorized for the request.
public
isAuthorized([ArrayAccess|array<string|int, mixed>|null $user = null ][, ServerRequest|null $request = null ]) : bool
Uses the configured Authorization adapters to check whether a user is authorized. Each adapter will be checked in sequence, if any of them return true, then the user will be authorized for the request.
Parameters
- $user : ArrayAccess|array<string|int, mixed>|null = null
-
The user to check the authorization of. If empty the user fetched from storage will be used.
- $request : ServerRequest|null = null
-
The request to authenticate for. If empty, the current request will be used.
Return values
bool —True if $user is authorized, otherwise false
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.
logout()
Log a user out.
public
logout() : string
Returns the logout action to redirect to. Triggers the Auth.logout
event
which the authenticate classes can listen for and perform custom logout logic.
Tags
Return values
string —Normalized config logoutRedirect
redirectUrl()
Get the URL a user should be redirected to upon login.
public
redirectUrl([array<string|int, mixed>|string|null $url = null ]) : string
Pass a URL in to set the destination a user should be redirected to upon logging in.
If no parameter is passed, gets the authentication redirect URL. The URL returned is as per following rules:
- Returns the normalized redirect URL from storage if it is present and for the same domain the current app is running on.
- If there is no URL returned from storage and there is a config
loginRedirect
, theloginRedirect
value is returned. - If there is no session and no
loginRedirect
, / is returned.
Parameters
- $url : array<string|int, mixed>|string|null = null
-
Optional URL to write as the login redirect URL.
Return values
string —Redirect URL
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
Return values
$thissetEventManager()
Returns the Cake\Event\EventManagerInterface instance for this object.
public
setEventManager(EventManagerInterface $eventManager) : $this
You can use this instance to register any new listeners or callbacks to the object events, or create your own events and trigger them at will.
Parameters
- $eventManager : EventManagerInterface
-
the eventManager to set
Return values
$thissetUser()
Set provided user info to storage as logged in user.
public
setUser(ArrayAccess|array<string|int, mixed> $user) : void
The storage class is configured using storage
config key or passing
instance to AuthComponent::storage().
Parameters
- $user : ArrayAccess|array<string|int, mixed>
-
User data.
Tags
startup()
Callback for Controller.startup event.
public
startup(EventInterface $event) : Response|null
Parameters
- $event : EventInterface
-
Event instance.
Return values
Response|nullstorage()
Get/set user record storage object.
public
storage([StorageInterface|null $storage = null ]) : StorageInterface|null
Parameters
- $storage : StorageInterface|null = null
-
Sets provided object as storage or if null returns configured storage object.
Return values
StorageInterface|nulluser()
Get the current user from storage.
public
user([string|null $key = null ]) : mixed|null
Parameters
- $key : string|null = null
-
Field to retrieve. Leave null to get entire User record.
Tags
Return values
mixed|null —Either User record or null if no user is logged in, or retrieved field if key is specified.
_configDelete()
Deletes a single config key.
protected
_configDelete(string $key) : void
Parameters
- $key : string
-
Key to delete.
Tags
_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
_getUrlToRedirectBackTo()
Returns the URL to redirect back to or / if not possible.
protected
_getUrlToRedirectBackTo() : string
This method takes the referrer into account if the request is not of type GET.
Return values
string_getUser()
Similar to AuthComponent::user() except if user is not found in configured storage, connected authentication objects will have their getUser() methods called.
protected
_getUser() : bool
This lets stateless authentication methods function correctly.
Return values
bool —true If a user can be found, false if one cannot.
_isAllowed()
Checks whether current action is accessible without authentication.
protected
_isAllowed(Controller $controller) : bool
Parameters
- $controller : Controller
-
A reference to the instantiating controller object
Return values
bool —True if action is accessible without authentication else false
_isLoginAction()
Normalizes config `loginAction` and checks if current request URL is same as login action.
protected
_isLoginAction(Controller $controller) : bool
Parameters
- $controller : Controller
-
A reference to the controller object.
Return values
bool —True if current action is login action else false.
_loginActionRedirectUrl()
Returns the URL of the login action to redirect to.
protected
_loginActionRedirectUrl() : array<string|int, mixed>|string
This includes the redirect query string if applicable.
Return values
array<string|int, mixed>|string_setDefaults()
Sets defaults for configs.
protected
_setDefaults() : void
_unauthenticated()
Handles unauthenticated access attempt. First the `unauthenticated()` method of the last authenticator in the chain will be called. The authenticator can handle sending response or redirection as appropriate and return `true` to indicate no further action is necessary. If authenticator returns null this method redirects user to login action.
protected
_unauthenticated(Controller $controller) : Response|null
Parameters
- $controller : Controller
-
A reference to the controller object.
Tags
Return values
Response|null —Null if current action is login action else response object returned by authenticate object or Controller::redirect().
_unauthorized()
Handle unauthorized access attempt
protected
_unauthorized(Controller $controller) : Response|null
Parameters
- $controller : Controller
-
A reference to the controller object