Class AuthComponent
Authentication control component class
Binds access control with user authentication and session management.
- CakeObject
- Component
- AuthComponent
Link: http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
Copyright: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
License: MIT License
Location: Cake/Controller/Component/AuthComponent.php
Constants summary
-
string
ALL
¶'all'
Properties summary
-
$_authenticateObjects
protectedObjects that will be used for authentication checks. -
$_authorizeObjects
protectedObjects that will be used for authorization checks. -
$_methods
protectedarray
Method list for bound controller. -
$_user
protected staticarray
The current user, used for stateless authentication when sessions are not available.
-
$ajaxLogin
publicstring
The name of an optional view element to render when an Ajax request is made with an invalid or expired session
-
$allowedActions
publicarray
Controller actions for which user validation is not required. -
$authError
publicstring|boolean
Error to display when user attempts to access an object or action to which they do not have access.
-
$authenticate
publicarray
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.
-
$authorize
publicmixed
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.
-
$components
publicarray
Other components utilized by AuthComponent -
$flash
publicarray
Settings to use when Auth needs to do a flash message with SessionComponent::setFlash(). Available keys are:
-
$loginAction
publicmixed
A URL (defined as a string or array) to the controller action that handles logins. Defaults to
/users/login
. -
$loginRedirect
publicmixed
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
publicmixed
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 AuthComponent::$loginAction.
-
$request
publicRequest object -
$response
publicResponse object -
$sessionKey
public staticstring
The session key name where the record of the current user is stored. Default key is "Auth.User". If you are using only stateless authenticators set this to false to ensure session is not started.
-
$unauthorizedRedirect
publicmixed
Controls handling of unauthorized access. - For default value
true
unauthorized user is redirected to the referrer URL or AuthComponent::$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.
Inherited Properties
Method Summary
-
_getUser() protected
Similar to AuthComponent::user() except if the session user cannot be found, connected authentication objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
-
_isAllowed() protected
Checks whether current action is accessible without authentication. -
_isLoginAction() protected
Normalizes $loginAction and checks if current request URL is same as login action. -
_setDefaults() protected
Attempts to introspect the correct values for object properties. -
_unauthenticated() protected
Handles unauthenticated access attempt. First the
unathenticated()
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 furthur action is necessary. If authenticator returns null this method redirects user to login action. If it's an ajax request and $ajaxLogin 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.
-
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. -
flash() public
Set a flash message. Uses the Session component, and values from AuthComponent::$flash. -
identify() public
Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
-
initialize() public
Initializes AuthComponent for use in the controller. -
isAuthorized() public
Check if the provided user is authorized for the request. -
loggedIn() public deprecated
Check whether or not the current user has data in the session, and is considered logged in. -
login() public
Log a user in. -
logout() public
Log a user out. -
mapActions() public deprecated
Maps action names to CRUD operations. -
password() public static deprecated
Hash a password with the application's salt value (as defined with Configure::write('Security.salt'); -
redirect() public deprecated
Backwards compatible alias for AuthComponent::redirectUrl(). -
redirectUrl() public
Get the URL a user should be redirected to upon login. -
startup() public
Main execution method. Handles redirecting of invalid users, and processing of login form data.
-
user() public static
Get the current user.
Method Detail
_getUser() protected ¶
_getUser( )
Similar to AuthComponent::user() except if the session user cannot be found, connected authentication objects will have their getUser() methods called. This lets stateless authentication methods function correctly.
Returns
True if a user can be found, false if one cannot.
_isAllowed() protected ¶
_isAllowed( Controller
$controller )
Checks whether current action is accessible without authentication.
Parameters
-
Controller
$controller - A reference to the instantiating controller object
Returns
True if action is accessible without authentication else false
_isLoginAction() protected ¶
_isLoginAction( Controller
$controller )
Normalizes $loginAction and checks if current request URL is same as login action.
Parameters
-
Controller
$controller - A reference to the controller object.
Returns
True if current action is login action else false.
_setDefaults() protected ¶
_setDefaults( )
Attempts to introspect the correct values for object properties.
Returns
True
_unauthenticated() protected ¶
_unauthenticated( Controller
$controller )
Handles unauthenticated access attempt. First the unathenticated()
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 furthur action is necessary. If authenticator returns null this
method redirects user to login action. If it's an ajax request and
$ajaxLogin is specified that element is rendered else a 403 http status code
is returned.
Parameters
-
Controller
$controller - A reference to the controller object.
Returns
True if current action is login action else false.
_unauthorized() protected ¶
_unauthorized( Controller
$controller )
Handle unauthorized access attempt
Parameters
-
Controller
$controller - A reference to the controller object
Returns
Returns false
Throws
See
allow() public ¶
allow( string|array|null $action = null )
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 var args.
$this->Auth->allow(array('edit', 'add'));
or
$this->Auth->allow('edit', 'add');
or
$this->Auth->allow();
to allow all actions
Parameters
- string|array|null $action optional null
- Controller action name or array of actions
Link
constructAuthenticate() public ¶
constructAuthenticate( )
Loads the configured authentication objects.
Returns
Either null on empty authenticate value, or an array of loaded objects.
Throws
constructAuthorize() public ¶
constructAuthorize( )
Loads the authorization objects configured.
Returns
Either null when authorize is empty, or the loaded authorization objects.
Throws
deny() public ¶
deny( string|array|null $action = null )
Removes items from the list of allowed/no authentication required actions.
You can use deny with either an array, or var args.
$this->Auth->deny(array('edit', 'add'));
or
$this->Auth->deny('edit', 'add');
or
$this->Auth->deny();
to remove all items from the allowed list
Parameters
- string|array|null $action optional null
- Controller action name or array of actions
See
Link
flash() public ¶
flash( string $message )
Set a flash message. Uses the Session component, and values from AuthComponent::$flash.
Parameters
- string $message
- The message to set.
identify() public ¶
identify( CakeRequest
$request , CakeResponse
$response )
Use the configured authentication adapters, and attempt to identify the user by credentials contained in $request.
Parameters
-
CakeRequest
$request - The request that contains authentication data.
-
CakeResponse
$response - The response
Returns
User record data, or false, if the user could not be identified.
initialize() public ¶
initialize( Controller
$controller )
Initializes AuthComponent for use in the controller.
Parameters
-
Controller
$controller - A reference to the instantiating controller object
Overrides
isAuthorized() public ¶
isAuthorized( array|null $user = null , CakeRequest
$request = null )
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
- array|null $user optional null
- The user to check the authorization of. If empty the user in the session will be used.
-
CakeRequest
$request optional null - The request to authenticate for. If empty, the current request will be used.
Returns
True if $user is authorized, otherwise false
loggedIn() public deprecated ¶
loggedIn( )
Check whether or not the current user has data in the session, and is considered logged in.
Deprecated
Returns
true if the user is logged in, false otherwise
login() public ¶
login( array|null $user = null )
Log a user in.
If a $user is provided that data will be stored as the logged in user. If $user
is empty or not
specified, the request will be used to identify a user. If the identification was successful,
the user record is written to the session key specified in AuthComponent::$sessionKey. Logging in
will also change the session id in order to help mitigate session replays.
Parameters
- array|null $user optional null
- Either an array of user data, or null to identify a user using the current request.
Returns
True on login success, false on failure
Link
logout() public ¶
logout( )
Log a user out.
Returns the logout action to redirect to. Triggers the logout() method of all the authenticate objects, so they can perform custom logout logic. AuthComponent will remove the session data, so there is no need to do that in an authentication object. Logging out will also renew the session id. This helps mitigate issues with session replays.
Returns
AuthComponent::$logoutRedirect
See
Link
mapActions() public deprecated ¶
mapActions( array $map = array() )
Maps action names to CRUD operations.
Used for controller-based authentication. Make sure to configure the authorize property before calling this method. As it delegates $map to all the attached authorize objects.
Deprecated
actionMap
config key on authorize objects insteadParameters
- array $map optional array()
- Actions to map
Returns
See
Link
password() public static deprecated ¶
password( string $password )
Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
This method is intended as a convenience wrapper for Security::hash(). If you want to use a hashing/encryption system not supported by that method, do not use this method.
Deprecated
Parameters
- string $password
- Password to hash
Returns
Hashed password
redirect() public deprecated ¶
redirect( string|array|null $url = null )
Backwards compatible alias for AuthComponent::redirectUrl().
Deprecated
Parameters
- string|array|null $url optional null
- Optional URL to write as the login redirect URL.
Returns
Redirect URL
redirectUrl() public ¶
redirectUrl( string|array|null $url = null )
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 URL from session Auth.redirect value if it is present and for the same domain the current app is running on.
- If there is no session value and there is a $loginRedirect, the $loginRedirect value is returned.
- If there is no session and no $loginRedirect, / is returned.
Parameters
- string|array|null $url optional null
- Optional URL to write as the login redirect URL.
Returns
Redirect URL
startup() public ¶
startup( Controller
$controller )
Main execution method. Handles redirecting of invalid users, and processing of login form data.
Parameters
-
Controller
$controller - A reference to the instantiating controller object
Returns
Overrides
user() public static ¶
user( string|null $key = null )
Get the current user.
Will prefer the static user cache over sessions. The static user cache is primarily used for stateless authentication. For stateful authentication, cookies + sessions will be used.
Parameters
- string|null $key optional null
- field to retrieve. Leave null to get entire User record
Returns
User record. or null if no user is logged in.
Link
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
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( string $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
- string $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
$_authenticateObjects ¶
BaseAuthenticate[]
Objects that will be used for authentication checks.
array()
$_authorizeObjects ¶
BaseAuthorize[]
Objects that will be used for authorization checks.
array()
$_user ¶
The current user, used for stateless authentication when sessions are not available.
array()
$ajaxLogin ¶
The name of an optional view element to render when an Ajax request is made with an invalid or expired session
null
$allowedActions ¶
Controller actions for which user validation is not required.
See
array()
$authError ¶
Error to display when user attempts to access an object or action to which they do not have access.
Link
null
$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->authenticate = array( 'Form' => array( 'userModel' => 'Users.User' ) );
Using the class name without 'Authenticate' as the key, you can pass in an array of settings for each authentication object. Additionally you can define settings that should be set to all authentications objects using the 'all' key:
$this->Auth->authenticate = array( 'all' => array( 'userModel' => 'Users.User', 'scope' => array('User.active' => 1) ), 'Form', 'Basic' );
You can also use AuthComponent::ALL instead of the string 'all'.
Link
array('Form')
$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->authorize = array( 'Crud' => array( 'actionPath' => 'controllers/' ) );
Using the class name without 'Authorize' as the key, you can pass in an array of settings for each authorization object. Additionally you can define settings that should be set to all authorization objects using the 'all' key:
$this->Auth->authorize = array( 'all' => array( 'actionPath' => 'controllers/' ), 'Crud', 'CustomAuth' );
You can also use AuthComponent::ALL instead of the string 'all'
Link
false
$components ¶
Other components utilized by AuthComponent
array('Session', 'Flash', 'RequestHandler')
$flash ¶
Settings to use when Auth needs to do a flash message with SessionComponent::setFlash(). Available keys are:
element
- The element to use, defaults to 'default'.key
- The key to use, defaults to 'auth'params
- The array of additional params to use, defaults to array()
array( 'element' => 'default', 'key' => 'auth', 'params' => array() )
$loginAction ¶
A URL (defined as a string or array) to the controller action that handles
logins. Defaults to /users/login
.
array( 'controller' => 'users', 'action' => 'login', 'plugin' => null )
$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.
Link
null
$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 AuthComponent::$loginAction.
See
AuthComponent::logout()
null
$sessionKey ¶
The session key name where the record of the current user is stored. Default key is "Auth.User". If you are using only stateless authenticators set this to false to ensure session is not started.
'Auth.User'
$unauthorizedRedirect ¶
Controls handling of unauthorized access.
- For default value true
unauthorized user is redirected to the referrer URL
or AuthComponent::$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.
true