CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.4 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.4
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

  • AclComponent
  • AuthComponent
  • CookieComponent
  • EmailComponent
  • PaginatorComponent
  • RequestHandlerComponent
  • SecurityComponent
  • SessionComponent

Class AuthComponent

Authentication control component class

Binds access control with user authentication and session management.

Object
Extended by Component
Extended by AuthComponent
Package: Cake\Controller\Component
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 protected
    array
    Objects that will be used for authentication checks.
  • $_authorizeObjects protected
    array
    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

  • $allowedActions public
    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.

  • $loginRedirect 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.

  • $logoutRedirect 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.

  • $request public
    CakeRequest
    Request object
  • $response public
    CakeResponse
    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.

  • $unauthorizedRedirect 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.

Inherited Properties

  • _Collection, _componentMap, settings

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.

  • 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
    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 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
boolean
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
boolean
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
boolean
True if current action is login action else false.

_setDefaults() protected ¶

_setDefaults( )

Attempts to introspect the correct values for object properties.

Returns
boolean
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
boolean
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
boolean
Returns false
Throws
ForbiddenException
See
AuthComponent::$unauthorizedRedirect

allow() public ¶

allow( string|array $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 $action optional null
Controller action name or array of actions
Link
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-public

constructAuthenticate() public ¶

constructAuthenticate( )

Loads the configured authentication objects.

Returns
mixed
either null on empty authenticate value, or an array of loaded objects.
Throws
CakeException

constructAuthorize() public ¶

constructAuthorize( )

Loads the authorization objects configured.

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

deny() public ¶

deny( string|array $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 $action optional null
Controller action name or array of actions
See
AuthComponent::allow()
Link
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#making-actions-require-authorization

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
array
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
Component::initialize()

isAuthorized() public ¶

isAuthorized( array $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 $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() public ¶

loggedIn( )

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

Returns
boolean
true if the user is logged in, false otherwise

login() public ¶

login( array $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 $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
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#identifying-users-and-logging-them-in

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
string
AuthComponent::$logoutRedirect
See
AuthComponent::$logoutRedirect
Link
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#logging-users-out

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

Parameters
array $map optional array()
Actions to map
See
BaseAuthorize::mapActions()
Link
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#mapping-actions-when-using-crudauthorize

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
Since 2.4. Use Security::hash() directly or a password hasher object.
Parameters
string $password
Password to hash
Returns
string
Hashed password

redirect() public deprecated ¶

redirect( string|array $url = null )

Backwards compatible alias for AuthComponent::redirectUrl().

Deprecated
2.3 Use AuthComponent::redirectUrl() instead
Parameters
string|array $url optional null
Optional URL to write as the login redirect URL.
Returns
string
Redirect URL

redirectUrl() public ¶

redirectUrl( string|array $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 $url optional null
Optional URL to write as the login redirect URL.
Returns
string
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
boolean
Overrides
Component::startup()

user() public static ¶

user( string $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 $key optional null
field to retrieve. Leave null to get entire User record
Returns
mixed
User record. or null if no user is logged in.
Link
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#accessing-the-logged-in-user

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
Object::__construct()

__get() 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() 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|
Either an array or null.
Link
http://book.cakephp.org/2.0/en/controllers/components.html#Component::beforeRedirect

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
http://book.cakephp.org/2.0/en/controllers/components.html#Component::beforeRender

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
http://book.cakephp.org/2.0/en/controllers/components.html#Component::shutdown

Methods inherited from Object

_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
mixed
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
boolean
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
mixed

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


toString() public ¶

toString( )

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

Returns
string
The name of this class

Properties detail

$_authenticateObjects ¶

protected array

Objects that will be used for authentication checks.

array()

$_authorizeObjects ¶

protected array

Objects that will be used for authorization checks.

array()

$_methods ¶

protected array

Method list for bound controller.

array()

$_user ¶

protected static array

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

array()

$ajaxLogin ¶

public string

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

null

$allowedActions ¶

public array

Controller actions for which user validation is not required.

See
AuthComponent::allow()
array()

$authError ¶

public string|boolean

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

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

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

{{{ $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
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
array('Form')

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

{{{ $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
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#authorization
false

$components ¶

public array

Other components utilized by AuthComponent

array('Session', 'RequestHandler')

$flash ¶

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

$loginAction ¶

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
)

$loginRedirect ¶

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
http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#AuthComponent::$loginRedirect
null

$logoutRedirect ¶

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

$request ¶

public CakeRequest

Request object

$response ¶

public CakeResponse

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.

'Auth.User'

$unauthorizedRedirect ¶

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
OpenHub
Rackspace
Rackspace
  • Business Solutions
  • Showcase
  • Documentation
  • Book
  • API
  • Videos
  • Reporting Security Issues
  • Privacy Policy
  • Logos & Trademarks
  • Community
  • Get Involved
  • Issues (GitHub)
  • Bakery
  • Featured Resources
  • Training
  • Meetups
  • My CakePHP
  • CakeFest
  • Newsletter
  • Linkedin
  • YouTube
  • Facebook
  • Twitter
  • Mastodon
  • Help & Support
  • Forum
  • Stack Overflow
  • Slack
  • Paid Support

Generated using CakePHP API Docs