Class AuthComponent

Authentication control component class

Binds access control with user authentication and session management.

CakeObject
Extended by Component
Extended by AuthComponent
Package: Cake\Controller\Component
Link: https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
Copyright: Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
License: MIT License
Location: Cake/Controller/Component/AuthComponent.php

Constants summary

  • string

    ALL
    'all'

Properties summary

  • Objects that will be used for authentication checks.
  • $_authorizeObjects protected
    Objects that will be used for authorization checks.
  • $_methods protected
    array
    Method list for bound controller.
  • $_user protected static
    array

    The current user, used for stateless authentication when sessions are not available.

  • $ajaxLogin public
    string

    The name of an optional view element to render when an Ajax request is made with an invalid or expired session

  • array
    Controller actions for which user validation is not required.
  • $authError public
    string|boolean

    Error to display when user attempts to access an object or action to which they do not have access.

  • $authenticate public
    array

    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 public
    mixed

    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 public
    array
    Other components utilized by AuthComponent
  • $flash public
    array

    Settings to use when Auth needs to do a flash message with SessionComponent::setFlash(). Available keys are:

  • $loginAction public
    mixed

    A URL (defined as a string or array) to the controller action that handles logins. Defaults to /users/login.

  • mixed

    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.

  • mixed

    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 public
    Request object
  • $response public
    Response object
  • $sessionKey public static
    string

    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.

  • mixed

    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 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.

  • _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.

  • Loads the configured authentication objects.
  • 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.
  • Check if the provided user is authorized for the request.
  • loggedIn() public
    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
    Maps action names to CRUD operations.
  • password() public static
    Hash a password with the application's salt value (as defined with Configure::write('Security.salt');
  • redirect() public
    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()source 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

boolean
True if a user can be found, false if one cannot.

_isAllowed()source protected

_isAllowed( Controller $controller )

Checks whether current action is accessible without authentication.

Parameters

Controller $controller
A reference to the instantiating controller object

Returns

boolean
True if action is accessible without authentication else false

_isLoginAction()source 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

boolean
True if current action is login action else false.

_setDefaults()source protected

_setDefaults( )

Attempts to introspect the correct values for object properties.

Returns

boolean
True

_unauthenticated()source 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

boolean
True if current action is login action else false.

_unauthorized()source protected

_unauthorized( Controller $controller )

Handle unauthorized access attempt

Parameters

Controller $controller
A reference to the controller object

Returns

boolean
Returns false

Throws

ForbiddenException

See

AuthComponent::$unauthorizedRedirect

allow()source 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

https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public

constructAuthenticate()source public

constructAuthenticate( )

Loads the configured authentication objects.

Returns

mixed
Either null on empty authenticate value, or an array of loaded objects.

Throws

CakeException

constructAuthorize()source public

constructAuthorize( )

Loads the authorization objects configured.

Returns

mixed
Either null when authorize is empty, or the loaded authorization objects.

Throws

CakeException

deny()source 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

AuthComponent::allow()

Link

https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization

flash()source 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()source 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

array
User record data, or false, if the user could not be identified.

initialize()source public

initialize( Controller $controller )

Initializes AuthComponent for use in the controller.

Parameters

Controller $controller
A reference to the instantiating controller object

Overrides

Component::initialize()

isAuthorized()source 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

boolean
True if $user is authorized, otherwise false

loggedIn()source public

loggedIn( )

Check whether or not the current user has data in the session, and is considered logged in.

Deprecated

3.0.0 Since 2.5. Use AuthComponent::user() directly.

Returns

boolean
true if the user is logged in, false otherwise

login()source 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

boolean
True on login success, false on failure

Link

https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in

logout()source 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

string
AuthComponent::$logoutRedirect

See

AuthComponent::$logoutRedirect

Link

https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out

mapActions()source public

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

3.0.0 Map actions using actionMap config key on authorize objects instead

Parameters

array $map optional array()
Actions to map

Returns

array

See

BaseAuthorize::mapActions()

Link

https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize

password()source public static

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

3.0.0 Since 2.4. Use Security::hash() directly or a password hasher object.

Parameters

string $password
Password to hash

Returns

string
Hashed password

redirect()source public

redirect( string|array|null $url null )

Backwards compatible alias for AuthComponent::redirectUrl().

Deprecated

3.0.0 Since 2.3.0, use AuthComponent::redirectUrl() instead

Parameters

string|array|null $url optional null
Optional URL to write as the login redirect URL.

Returns

string
Redirect URL

redirectUrl()source 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

string
Redirect URL

startup()source 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

boolean

Overrides

Component::startup()

user()source 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

mixed|null
User record. or null if no user is logged in.

Link

https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user

Methods inherited from Component

__construct()source 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

CakeObject::__construct()

__get()source public

__get( string $name )

Magic method for lazy loading $components.

Parameters

string $name
Name of component to get.

Returns

mixed
A Component object or null.

beforeRedirect()source 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 redirect
  • exit 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

array|null
Either an array or null.

Link

https://book.cakephp.org/2.0/en/controllers/components.html#Component::beforeRedirect

beforeRender()source 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

https://book.cakephp.org/2.0/en/controllers/components.html#Component::beforeRender

shutdown()source 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

https://book.cakephp.org/2.0/en/controllers/components.html#Component::shutdown

Methods inherited from CakeObject

_mergeVars()source 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()source 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()source 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()source 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

mixed
Returns the result of the method call

log()source 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

boolean
Success of log write

requestAction()source 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

mixed

Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.


toString()source public

toString( )

CakeObject-to-string conversion. Each class can override this method as necessary.

Returns

string
The name of this class

Properties detail

$_authenticateObjectssource

protected BaseAuthenticate[]

Objects that will be used for authentication checks.

array()

$_authorizeObjectssource

protected BaseAuthorize[]

Objects that will be used for authorization checks.

array()

$_methodssource

protected array

Method list for bound controller.

array()

$_usersource

protected static array

The current user, used for stateless authentication when sessions are not available.

array()

$ajaxLoginsource

public string

The name of an optional view element to render when an Ajax request is made with an invalid or expired session

null

$allowedActionssource

public array

Controller actions for which user validation is not required.

See

AuthComponent::allow()
array()

$authErrorsource

public string|boolean

Error to display when user attempts to access an object or action to which they do not have access.

Link

https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$authError
null

$authenticatesource

public array

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

https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
array('Form')

$authorizesource

public mixed

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

https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#authorization
false

$componentssource

public array

Other components utilized by AuthComponent

array('Session', 'Flash', 'RequestHandler')

$flashsource

public array

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()
)

$loginActionsource

public mixed

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
)

$loginRedirectsource

public mixed

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

https://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$loginRedirect
null

$logoutRedirectsource

public mixed

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::$loginAction
AuthComponent::logout()
null

$requestsource

public CakeRequest

Request object

$responsesource

public CakeResponse

Response object

$sessionKeysource

public static string

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'

$unauthorizedRedirectsource

public mixed

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

© 2005–2017 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
https://api.cakephp.org/2.10/class-AuthComponent.html