Class AuthComponent
Authentication control component class.
Binds access control with user authentication and session management.
Link: https://book.cakephp.org/3.0/en/controllers/components/authentication.html
Constants
Property Summary
-
$Flash public @property
Cake\Controller\Component\FlashComponent
-
$RequestHandler public @property
Cake\Controller\Component\RequestHandlerComponent
-
$_authenticateObjects protected
Cake\Auth\BaseAuthenticate[]
Objects that will be used for authentication checks.
-
$_authenticationProvider protected
Cake\Auth\BaseAuthenticate
The instance of the Authenticate provider that was used for successfully logging in the current user after calling
login()
in the same request -
$_authorizationProvider protected
Cake\Auth\BaseAuthorize
The instance of the Authorize provider that was used to grant access to the current user to the URL they are requesting.
-
$_authorizeObjects protected
Cake\Auth\BaseAuthorize[]
Objects that will be used for authorization checks.
-
$_componentMap protected
array
A component lookup table used to lazy load component objects.
-
$_config protected
array
Runtime config
-
$_configInitialized protected
bool
Whether the config property has already been configured with defaults
-
$_defaultConfig protected
array
Default config
-
$_eventClass protected
string
Default class name for new event objects.
-
$_eventManager protected
Cake\Event\EventManager
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
-
$_registry protected
Cake\Controller\ComponentRegistry
Component registry class used to lazy load components.
-
$_storage protected
Cake\Auth\Storage\StorageInterface|null
Storage object.
-
$allowedActions public
array
Controller actions for which user validation is not required.
-
$components public
array
Other components utilized by AuthComponent
-
$request public
Cake\Http\ServerRequest
Request object
-
$response public
Cake\Http\Response
Response object
-
$session public deprecated
Cake\Network\Session
Instance of the Session object
Method Summary
-
__construct() public
Constructor
-
__debugInfo() public
Returns an array that can be used to describe the internal state of this object.
-
__get() public
Magic accessor for backward compatibility for property
$sessionKey
. -
__set() public
Magic setter for backward compatibility for property
$sessionKey
. -
_configDelete() protected
Deletes a single config key.
-
_configRead() protected
Reads a config key.
-
_configWrite() protected
Writes a config key.
-
_getUrlToRedirectBackTo() protected
Returns the URL to redirect back to or / if not possible.
-
_getUser() protected
Similar to AuthComponent::user() except if user is not found in configured storage, connected authentication objects will have their getUser() methods called.
-
_isAllowed() protected
Checks whether current action is accessible without authentication.
-
_isLoginAction() protected
Normalizes config
loginAction
and checks if current request URL is same as login action. -
_loginActionRedirectUrl() protected
Returns the URL of the login action to redirect to.
-
_setDefaults() protected
Sets defaults for configs.
-
_unauthenticated() protected
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 returntrue
to indicate no further action is necessary. If authenticator returns null this method redirects user to login action. If it's an AJAX request and configajaxLogin
is specified that element is rendered else a 403 HTTP status code is returned. -
_unauthorized() protected
Handle unauthorized access attempt
-
allow() public
Takes a list of actions in the current controller for which authentication is not required, or no parameters to allow all actions.
-
authCheck() public
Main execution method, handles initial authentication check and redirection of invalid users.
-
authenticationProvider() public
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() public
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.
-
config() public deprecated
Gets/Sets the config.
-
configShallow() public
Merge provided config with existing config. Unlike
config()
which does a recursive merge for nested keys, this method does a simple merge. -
constructAuthenticate() public
Loads the configured authentication objects.
-
constructAuthorize() public
Loads the authorization objects configured.
-
deny() public
Removes items from the list of allowed/no authentication required actions.
-
dispatchEvent() public
Wrapper for creating and dispatching events.
-
eventManager() public
Returns the Cake\Event\EventManager manager instance for this object.
-
flash() public
Set a flash message. Uses the Flash component with values from
flash
config. -
getAuthenticate() public
Getter for authenticate objects. Will return a particular authenticate object.
-
getAuthorize() public
Getter for authorize objects. Will return a particular authorize object.
-
getConfig() public
Returns the config.
-
getController() public
Get the controller this component is bound to.
-
identify() public
Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
-
implementedEvents() public
Events supported by this component.
-
initialize() public
Initialize properties.
-
isAuthorized() public
Check if the provided user is authorized for the request.
-
log() public
Convenience method to write a message to Log. See Log::write() for more information on writing to logs.
-
logout() public
Log a user out.
-
redirectUrl() public
Get the URL a user should be redirected to upon login.
-
setConfig() public
Sets the config.
-
setUser() public
Set provided user info to storage as logged in user.
-
startup() public
Callback for Controller.startup event.
-
storage() public
Get/set user record storage object.
-
user() public
Get the current user from storage.
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(): array
Returns an array that can be used to describe the internal state of this object.
Returns
array
__get() ¶ public
__get(string $name): mixed
Magic accessor for backward compatibility for property $sessionKey
.
Parameters
-
string
$name Property name
Returns
mixed
__set() ¶ public
__set(string $name, mixed $value): void
Magic setter for backward compatibility for property $sessionKey
.
Parameters
-
string
$name Property name.
-
mixed
$value Value to set.
Returns
void
_configDelete() ¶ protected
_configDelete(string $key): void
Deletes a single config key.
Parameters
-
string
$key Key to delete.
Returns
void
Throws
Cake\Core\Exception\Exception
if attempting to clobber existing config
_configRead() ¶ protected
_configRead(string|null $key): mixed
Reads a config key.
Parameters
-
string|null
$key Key to read.
Returns
mixed
_configWrite() ¶ protected
_configWrite(string|array $key, mixed $value, bool|string $merge = false): void
Writes a config key.
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
void
Throws
Cake\Core\Exception\Exception
if attempting to clobber existing config
_getUrlToRedirectBackTo() ¶ protected
_getUrlToRedirectBackTo(): string
Returns the URL to redirect back to or / if not possible.
This method takes the referrer into account if the request is not of type GET.
Returns
string
_getUser() ¶ protected
_getUser(): bool
Similar to AuthComponent::user() except if user is not found in configured storage, connected authentication objects will have their getUser() methods called.
This lets stateless authentication methods function correctly.
Returns
bool
_isAllowed() ¶ protected
_isAllowed(Cake\Controller\Controller $controller): bool
Checks whether current action is accessible without authentication.
Parameters
-
Cake\Controller\Controller
$controller A reference to the instantiating controller object
Returns
bool
_isLoginAction() ¶ protected
_isLoginAction(Cake\Controller\Controller $controller): bool
Normalizes config loginAction
and checks if current request URL is same as login action.
Parameters
-
Cake\Controller\Controller
$controller A reference to the controller object.
Returns
bool
_loginActionRedirectUrl() ¶ protected
_loginActionRedirectUrl(): array|string
Returns the URL of the login action to redirect to.
This includes the redirect query string if applicable.
Returns
array|string
_unauthenticated() ¶ protected
_unauthenticated(Cake\Controller\Controller $controller): Cake\Http\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. If it's an AJAX request and config
ajaxLogin
is specified that element is rendered else a 403 HTTP status code
is returned.
Parameters
-
Cake\Controller\Controller
$controller A reference to the controller object.
Returns
Cake\Http\Response|null
Throws
Cake\Core\Exception\Exception
_unauthorized() ¶ protected
_unauthorized(Cake\Controller\Controller $controller): Cake\Http\Response
Handle unauthorized access attempt
Parameters
-
Cake\Controller\Controller
$controller A reference to the controller object
Returns
Cake\Http\Response
Throws
Cake\Network\Exception\ForbiddenException
allow() ¶ public
allow(string|array|null $actions = null): void
Takes a list of actions in the current controller for which authentication is not required, or no parameters to allow all actions.
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
-
string|array|null
$actions optional Controller action name or array of actions
Returns
void
Links
authCheck() ¶ public
authCheck(Cake\Event\Event $event): Cake\Http\Response|null
Main execution method, handles initial authentication check and redirection of invalid users.
The auth check is done when event name is same as the one configured in
checkAuthIn
config.
Parameters
-
Cake\Event\Event
$event Event instance.
Returns
Cake\Http\Response|null
authenticationProvider() ¶ public
authenticationProvider(): Cake\Auth\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.
Returns
Cake\Auth\BaseAuthenticate|null
authorizationProvider() ¶ public
authorizationProvider(): Cake\Auth\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.
Returns
Cake\Auth\BaseAuthorize|null
config() ¶ public
config(string|array|null $key = null, mixed|null $value = null, bool $merge = true): mixed
Gets/Sets the config.
Usage
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
mixed
Throws
Cake\Core\Exception\Exception
When trying to set a key that is invalid.
configShallow() ¶ public
configShallow(string|array $key, mixed|null $value = null): $this
Merge 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->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
-
string|array
$key The key to set, or a complete array of configs.
-
mixed|null
$value optional The value to set.
Returns
$this
constructAuthenticate() ¶ public
constructAuthenticate(): array|null
Loads the configured authentication objects.
Returns
array|null
Throws
Cake\Core\Exception\Exception
constructAuthorize() ¶ public
constructAuthorize(): array|null
Loads the authorization objects configured.
Returns
array|null
Throws
Cake\Core\Exception\Exception
deny() ¶ public
deny(string|array|null $actions = null): void
Removes items from the list of allowed/no authentication required actions.
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
-
string|array|null
$actions optional Controller action name or array of actions
Returns
void
See Also
Links
dispatchEvent() ¶ public
dispatchEvent(string $name, array|null $data = null, object|null $subject = null): Cake\Event\Event
Wrapper for creating and dispatching events.
Returns a dispatched event.
Parameters
-
string
$name Name of the event.
-
array|null
$data optional Any value you wish to be transported with this event to it can be read by listeners.
-
object|null
$subject optional The object that this event applies to ($this by default).
Returns
Cake\Event\Event
eventManager() ¶ public
eventManager(Cake\Event\EventManager|null $eventManager = null): Cake\Event\EventManager
Returns the Cake\Event\EventManager manager instance for this object.
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
-
Cake\Event\EventManager|null
$eventManager optional the eventManager to set
Returns
Cake\Event\EventManager
flash() ¶ public
flash(string $message): void
Set a flash message. Uses the Flash component with values from flash
config.
Parameters
-
string
$message The message to set.
Returns
void
getAuthenticate() ¶ public
getAuthenticate(string $alias): Cake\Auth\BaseAuthenticate|null
Getter for authenticate objects. Will return a particular authenticate object.
Parameters
-
string
$alias Alias for the authenticate object
Returns
Cake\Auth\BaseAuthenticate|null
getAuthorize() ¶ public
getAuthorize(string $alias): Cake\Auth\BaseAuthorize|null
Getter for authorize objects. Will return a particular authorize object.
Parameters
-
string
$alias Alias for the authorize object
Returns
Cake\Auth\BaseAuthorize|null
getConfig() ¶ public
getConfig(string|null $key = null): mixed
Returns the config.
Usage
Reading the whole config:
$this->getConfig();
Reading a specific value:
$this->getConfig('key');
Reading a nested value:
$this->getConfig('some.nested.key');
Parameters
-
string|null
$key optional The key to get or null for the whole config.
Returns
mixed
getController() ¶ public
getController(): Cake\Controller\Controller
Get the controller this component is bound to.
Returns
Cake\Controller\Controller
identify() ¶ public
identify(): array|bool
Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
Triggers Auth.afterIdentify
event which the authenticate classes can listen
to.
Returns
array|bool
implementedEvents() ¶ public
implementedEvents(): array
Events 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
array
initialize() ¶ public
initialize(array $config): void
Initialize properties.
Implement this method to avoid having to overwrite the constructor and call parent.
Parameters
-
array
$config The config data.
Returns
void
isAuthorized() ¶ public
isAuthorized(arrayArrayAccess|null $user = null, Cake\Http\ServerRequest|null $request = null): bool
Check if the provided user is authorized for the request.
Uses the configured Authorization adapters to check whether or not 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
-
arrayArrayAccess|null
$user optional The user to check the authorization of. If empty the user fetched from storage will be used.
-
Cake\Http\ServerRequest|null
$request optional The request to authenticate for. If empty, the current request will be used.
Returns
bool
log() ¶ public
log(mixed $msg, int|string $level = LogLevel::ERROR, string|array $context = []): bool
Convenience 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
bool
logout() ¶ public
logout(): string
Log a user out.
Returns the logout action to redirect to. Triggers the Auth.logout
event
which the authenticate classes can listen for and perform custom logout logic.
Returns
string
Links
redirectUrl() ¶ public
redirectUrl(string|array|null $url = null): string
Get the URL a user should be redirected to upon login.
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.
- If there is no URL returned from storage and there is a config
Parameters
-
string|array|null
$url optional Optional URL to write as the login redirect URL.
Returns
string
setConfig() ¶ public
setConfig(string|array $key, mixed|null $value = null, bool $merge = true): $this
Sets the config.
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
-
string|array
$key The key to 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
$this
Throws
Cake\Core\Exception\Exception
When trying to set a key that is invalid.
setUser() ¶ public
setUser(arrayArrayAccess $user): void
Set provided user info to storage as logged in user.
The storage class is configured using storage
config key or passing
instance to AuthComponent::storage().
Parameters
-
arrayArrayAccess
$user User data.
Returns
void
Links
startup() ¶ public
startup(Cake\Event\Event $event): Cake\Http\Response|null
Callback for Controller.startup event.
Parameters
-
Cake\Event\Event
$event Event instance.
Returns
Cake\Http\Response|null
storage() ¶ public
storage(Cake\Auth\Storage\StorageInterface|null $storage = null): Cake\Auth\Storage\StorageInterface|null
Get/set user record storage object.
Parameters
-
Cake\Auth\Storage\StorageInterface|null
$storage optional Sets provided object as storage or if null returns configured storage object.
Returns
Cake\Auth\Storage\StorageInterface|null
user() ¶ public
user(string|null $key = null): mixed|null
Get the current user from storage.
Parameters
-
string|null
$key optional Field to retrieve. Leave null to get entire User record.
Returns
mixed|null
Links
Property Detail
$_authenticateObjects ¶ protected
Objects that will be used for authentication checks.
Type
Cake\Auth\BaseAuthenticate[]
$_authenticationProvider ¶ protected
The instance of the Authenticate provider that was used for
successfully logging in the current user after calling login()
in the same request
Type
Cake\Auth\BaseAuthenticate
$_authorizationProvider ¶ protected
The instance of the Authorize provider that was used to grant access to the current user to the URL they are requesting.
Type
Cake\Auth\BaseAuthorize
$_authorizeObjects ¶ protected
Objects that will be used for authorization checks.
Type
Cake\Auth\BaseAuthorize[]
$_configInitialized ¶ protected
Whether the config property has already been configured with defaults
Type
bool
$_defaultConfig ¶ protected
Default config
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'
]);
-
- The name of an optional view element to render when an Ajax request is made with an invalid or expired session. This option is deprecated since 3.3.6. Your client side code should instead check for 403 status code and show appropriate login form.ajaxLogin
-
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.
-
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.
Type
array
$_eventManager ¶ protected
Instance of the Cake\Event\EventManager this object is using to dispatch inner events.
Type
Cake\Event\EventManager
$_registry ¶ protected
Component registry class used to lazy load components.
Type
Cake\Controller\ComponentRegistry