PHP Class Cake\Controller\Component\AuthComponent

Binds access control with user authentication and session management.
Inheritance: extends Cake\Controller\Component, use trait Cake\Event\EventDispatcherTrait
Show file Open project: cakephp/cakephp Class Usage Examples

Public Properties

Property Type Description
$allowedActions array Controller actions for which user validation is not required.
$components array Other components utilized by AuthComponent
$request Cake\Network\Request Request object
$response Cake\Network\Response Response object
$session Cake\Network\Session Instance of the Session object

Protected Properties

Property Type Description
$_authenticateObjects Cake\Auth\BaseAuthenticate[] Objects that will be used for authentication checks.
$_authenticationProvider 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 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 Cake\Auth\BaseAuthorize[] Objects that will be used for authorization checks.
$_defaultConfig array - 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->config('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->config('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->config('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->config('authorize', [ AuthComponent::ALL => [ 'actionPath' => 'controllers/' ], 'Crud', 'CustomAuth' ]); - ~~ajaxLogin~~ - 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. - 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 the loginAction 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 in loginRedirect. - 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 from AuthComponent::logout(). Defaults to loginAction. - 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.
$_storage Cake\Auth\Storage\StorageInterface Storage object.

Public Methods

Method Description
__get ( string $name ) : mixed Magic accessor for backward compatibility for property $sessionKey.
__set ( string $name, mixed $value ) : void Magic setter for backward compatibility for property $sessionKey.
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.
authCheck ( Cake\Event\Event $event ) : Response | null Main execution method, handles initial authentication check and redirection of invalid users.
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.
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.
constructAuthenticate ( ) : array | null Loads the configured authentication objects.
constructAuthorize ( ) : array | null Loads the authorization objects configured.
deny ( string | array | null $actions = null ) : void Removes items from the list of allowed/no authentication required actions.
flash ( string $message ) : void Set a flash message. Uses the Flash component with values from flash config.
getAuthenticate ( string $alias ) : Cake\Auth\BaseAuthenticate | null Getter for authenticate objects. Will return a particular authenticate object.
getAuthorize ( string $alias ) : Cake\Auth\BaseAuthorize | null Getter for authorize objects. Will return a particular authorize object.
identify ( ) : array | boolean Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
implementedEvents ( ) : array Events supported by this component.
initialize ( array $config ) : void Initialize properties.
isAuthorized ( array | ArrayAccess | null $user = null, Cake\Network\Request $request = null ) : boolean Check if the provided user is authorized for the request.
logout ( ) : string Log a user out.
redirectUrl ( string | array | null $url = null ) : string Get the URL a user should be redirected to upon login.
setUser ( array | ArrayAccess $user ) : void Set provided user info to storage as logged in user.
startup ( Cake\Event\Event $event ) : Response | null Callback for Controller.startup event.
storage ( Cake\Auth\Storage\StorageInterface $storage = null ) : Cake\Auth\Storage\StorageInterface | null Get/set user record storage object.
user ( string | null $key = null ) : mixed | null Get the current user from storage.

Protected Methods

Method Description
_getUser ( ) : boolean Similar to AuthComponent::user() except if user is not found in configured storage, connected authentication objects will have their getUser() methods called.
_isAllowed ( Controller $controller ) : boolean Checks whether current action is accessible without authentication.
_isLoginAction ( Controller $controller ) : boolean Normalizes config loginAction and checks if current request URL is same as login action.
_setDefaults ( ) : void Sets defaults for configs.
_unauthenticated ( Controller $controller ) : 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.
_unauthorized ( Controller $controller ) : Response Handle unauthorized access attempt

Method Details

__get() public method

Magic accessor for backward compatibility for property $sessionKey.
public __get ( string $name ) : mixed
$name string Property name
return mixed

__set() public method

Magic setter for backward compatibility for property $sessionKey.
public __set ( string $name, mixed $value ) : void
$name string Property name.
$value mixed Value to set.
return void

_getUser() protected method

This lets stateless authentication methods function correctly.
protected _getUser ( ) : boolean
return boolean true If a user can be found, false if one cannot.

_isAllowed() protected method

Checks whether current action is accessible without authentication.
protected _isAllowed ( Controller $controller ) : boolean
$controller Cake\Controller\Controller A reference to the instantiating controller object
return boolean True if action is accessible without authentication else false

_isLoginAction() protected method

Normalizes config loginAction and checks if current request URL is same as login action.
protected _isLoginAction ( Controller $controller ) : boolean
$controller Cake\Controller\Controller A reference to the controller object.
return boolean True if current action is login action else false.

_setDefaults() protected method

Sets defaults for configs.
protected _setDefaults ( ) : void
return void

_unauthenticated() protected method

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.
protected _unauthenticated ( Controller $controller ) : Response | null
$controller Cake\Controller\Controller A reference to the controller object.
return Cake\Network\Response | null Null if current action is login action else response object returned by authenticate object or Controller::redirect().

_unauthorized() protected method

Handle unauthorized access attempt
protected _unauthorized ( Controller $controller ) : Response
$controller Cake\Controller\Controller A reference to the controller object
return Cake\Network\Response

allow() public method

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();
public allow ( string | array | null $actions = null ) : void
$actions string | array | null Controller action name or array of actions
return void

authCheck() public method

The auth check is done when event name is same as the one configured in checkAuthIn config.
public authCheck ( Cake\Event\Event $event ) : Response | null
$event Cake\Event\Event Event instance.
return Cake\Network\Response | null

authenticationProvider() public method

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 ( ) : Cake\Auth\BaseAuthenticate | null
return Cake\Auth\BaseAuthenticate | null

authorizationProvider() public method

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 ( ) : Cake\Auth\BaseAuthorize | null
return Cake\Auth\BaseAuthorize | null

constructAuthenticate() public method

Loads the configured authentication objects.
public constructAuthenticate ( ) : array | null
return array | null The loaded authorization objects, or null on empty authenticate value.

constructAuthorize() public method

Loads the authorization objects configured.
public constructAuthorize ( ) : array | null
return array | null The loaded authorization objects, or null when authorize is empty.

deny() public method

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
public deny ( string | array | null $actions = null ) : void
$actions string | array | null Controller action name or array of actions
return void

flash() public method

Set a flash message. Uses the Flash component with values from flash config.
public flash ( string $message ) : void
$message string The message to set.
return void

getAuthenticate() public method

Getter for authenticate objects. Will return a particular authenticate object.
public getAuthenticate ( string $alias ) : Cake\Auth\BaseAuthenticate | null
$alias string Alias for the authenticate object
return Cake\Auth\BaseAuthenticate | null

getAuthorize() public method

Getter for authorize objects. Will return a particular authorize object.
public getAuthorize ( string $alias ) : Cake\Auth\BaseAuthorize | null
$alias string Alias for the authorize object
return Cake\Auth\BaseAuthorize | null

identify() public method

Triggers Auth.afterIdentify event which the authenticate classes can listen to.
public identify ( ) : array | boolean
return array | boolean User record data, or false, if the user could not be identified.

implementedEvents() public method

Events supported by this component.
public implementedEvents ( ) : array
return array

initialize() public method

Initialize properties.
public initialize ( array $config ) : void
$config array The config data.
return void

isAuthorized() public method

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.
public isAuthorized ( array | ArrayAccess | null $user = null, Cake\Network\Request $request = null ) : boolean
$user array | ArrayAccess | null The user to check the authorization of. If empty the user fetched from storage will be used.
$request Cake\Network\Request The request to authenticate for. If empty, the current request will be used.
return boolean True if $user is authorized, otherwise false

logout() public method

Returns the logout action to redirect to. Triggers the Auth.logout event which the authenticate classes can listen for and perform custom logout logic.
public logout ( ) : string
return string Normalized config `logoutRedirect`

redirectUrl() public method

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, the loginRedirect value is returned. - If there is no session and no loginRedirect, / is returned.
public redirectUrl ( string | array | null $url = null ) : string
$url string | array | null Optional URL to write as the login redirect URL.
return string Redirect URL

setUser() public method

The storage class is configured using storage config key or passing instance to AuthComponent::storage().
public setUser ( array | ArrayAccess $user ) : void
$user array | ArrayAccess User data.
return void

startup() public method

Callback for Controller.startup event.
public startup ( Cake\Event\Event $event ) : Response | null
$event Cake\Event\Event Event instance.
return Cake\Network\Response | null

storage() public method

Get/set user record storage object.
public storage ( Cake\Auth\Storage\StorageInterface $storage = null ) : Cake\Auth\Storage\StorageInterface | null
$storage Cake\Auth\Storage\StorageInterface Sets provided object as storage or if null returns configured storage object.
return Cake\Auth\Storage\StorageInterface | null

user() public method

Get the current user from storage.
public user ( string | null $key = null ) : mixed | null
$key string | null Field to retrieve. Leave null to get entire User record.
return mixed | null Either User record or null if no user is logged in, or retrieved field if key is specified.

Property Details

$_authenticateObjects protected property

Objects that will be used for authentication checks.
protected BaseAuthenticate[],Cake\Auth $_authenticateObjects
return Cake\Auth\BaseAuthenticate[]

$_authenticationProvider protected property

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,Cake\Auth $_authenticationProvider
return Cake\Auth\BaseAuthenticate

$_authorizationProvider protected property

The instance of the Authorize provider that was used to grant access to the current user to the URL they are requesting.
protected BaseAuthorize,Cake\Auth $_authorizationProvider
return Cake\Auth\BaseAuthorize

$_authorizeObjects protected property

Objects that will be used for authorization checks.
protected BaseAuthorize[],Cake\Auth $_authorizeObjects
return Cake\Auth\BaseAuthorize[]

$_defaultConfig protected property

- 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->config('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->config('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->config('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->config('authorize', [ AuthComponent::ALL => [ 'actionPath' => 'controllers/' ], 'Crud', 'CustomAuth' ]); - ~~ajaxLogin~~ - 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. - 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 the loginAction 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 in loginRedirect. - 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 from AuthComponent::logout(). Defaults to loginAction. - 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.
protected array $_defaultConfig
return array

$_storage protected property

Storage object.
protected StorageInterface,Cake\Auth\Storage $_storage
return Cake\Auth\Storage\StorageInterface

$allowedActions public property

Controller actions for which user validation is not required.
See also: Cake\Controller\Component\AuthComponent::allow()
public array $allowedActions
return array

$components public property

Other components utilized by AuthComponent
public array $components
return array

$request public property

Request object
public Request,Cake\Network $request
return Cake\Network\Request

$response public property

Response object
public Response,Cake\Network $response
return Cake\Network\Response

$session public property

Instance of the Session object
Deprecation: 3.1.0 Will be removed in 4.0
public Session,Cake\Network $session
return Cake\Network\Session