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

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.5
      • 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

  • AbstractPasswordHasher
  • ActionsAuthorize
  • BaseAuthenticate
  • BaseAuthorize
  • BasicAuthenticate
  • BlowfishAuthenticate
  • BlowfishPasswordHasher
  • ControllerAuthorize
  • CrudAuthorize
  • DigestAuthenticate
  • FormAuthenticate
  • SimplePasswordHasher
  1: <?php
  2: /**
  3:  * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4:  * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5:  *
  6:  * Licensed under The MIT License
  7:  * For full copyright and license information, please see the LICENSE.txt
  8:  * Redistributions of files must retain the above copyright notice.
  9:  *
 10:  * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 11:  * @link          http://cakephp.org CakePHP(tm) Project
 12:  * @license       http://www.opensource.org/licenses/mit-license.php MIT License
 13:  */
 14: 
 15: App::uses('BasicAuthenticate', 'Controller/Component/Auth');
 16: 
 17: /**
 18:  * Digest Authentication adapter for AuthComponent.
 19:  *
 20:  * Provides Digest HTTP authentication support for AuthComponent. Unlike most AuthComponent adapters,
 21:  * DigestAuthenticate requires a special password hash that conforms to RFC2617. You can create this
 22:  * password using `DigestAuthenticate::password()`. If you wish to use digest authentication alongside other
 23:  * authentication methods, its recommended that you store the digest authentication separately.
 24:  *
 25:  * Clients using Digest Authentication must support cookies. Since AuthComponent identifies users based
 26:  * on Session contents, clients without support for cookies will not function properly.
 27:  *
 28:  * ### Using Digest auth
 29:  *
 30:  * In your controller's components array, add auth + the required settings.
 31:  * {{{
 32:  *  public $components = array(
 33:  *      'Auth' => array(
 34:  *          'authenticate' => array('Digest')
 35:  *      )
 36:  *  );
 37:  * }}}
 38:  *
 39:  * In your login function just call `$this->Auth->login()` without any checks for POST data. This
 40:  * will send the authentication headers, and trigger the login dialog in the browser/client.
 41:  *
 42:  * ### Generating passwords compatible with Digest authentication.
 43:  *
 44:  * Due to the Digest authentication specification, digest auth requires a special password value. You
 45:  * can generate this password using `DigestAuthenticate::password()`
 46:  *
 47:  * `$digestPass = DigestAuthenticate::password($username, env('SERVER_NAME'), $password);`
 48:  *
 49:  * Its recommended that you store this digest auth only password separate from password hashes used for other
 50:  * login methods. For example `User.digest_pass` could be used for a digest password, while `User.password` would
 51:  * store the password hash for use with other methods like Basic or Form.
 52:  *
 53:  * @package       Cake.Controller.Component.Auth
 54:  * @since 2.0
 55:  */
 56: class DigestAuthenticate extends BasicAuthenticate {
 57: 
 58: /**
 59:  * Settings for this object.
 60:  *
 61:  * - `fields` The fields to use to identify a user by.
 62:  * - `userModel` The model name of the User, defaults to User.
 63:  * - `scope` Additional conditions to use when looking up and authenticating users,
 64:  *    i.e. `array('User.is_active' => 1).`
 65:  * - `recursive` The value of the recursive key passed to find(). Defaults to 0.
 66:  * - `contain` Extra models to contain and store in session.
 67:  * - `realm` The realm authentication is for, Defaults to the servername.
 68:  * - `nonce` A nonce used for authentication. Defaults to `uniqid()`.
 69:  * - `qop` Defaults to auth, no other values are supported at this time.
 70:  * - `opaque` A string that must be returned unchanged by clients.
 71:  *    Defaults to `md5($settings['realm'])`
 72:  *
 73:  * @var array
 74:  */
 75:     public $settings = array(
 76:         'fields' => array(
 77:             'username' => 'username',
 78:             'password' => 'password'
 79:         ),
 80:         'userModel' => 'User',
 81:         'scope' => array(),
 82:         'recursive' => 0,
 83:         'contain' => null,
 84:         'realm' => '',
 85:         'qop' => 'auth',
 86:         'nonce' => '',
 87:         'opaque' => '',
 88:         'passwordHasher' => 'Simple',
 89:     );
 90: 
 91: /**
 92:  * Constructor, completes configuration for digest authentication.
 93:  *
 94:  * @param ComponentCollection $collection The Component collection used on this request.
 95:  * @param array $settings An array of settings.
 96:  */
 97:     public function __construct(ComponentCollection $collection, $settings) {
 98:         parent::__construct($collection, $settings);
 99:         if (empty($this->settings['nonce'])) {
100:             $this->settings['nonce'] = uniqid('');
101:         }
102:         if (empty($this->settings['opaque'])) {
103:             $this->settings['opaque'] = md5($this->settings['realm']);
104:         }
105:     }
106: 
107: /**
108:  * Get a user based on information in the request. Used by cookie-less auth for stateless clients.
109:  *
110:  * @param CakeRequest $request Request object.
111:  * @return mixed Either false or an array of user information
112:  */
113:     public function getUser(CakeRequest $request) {
114:         $digest = $this->_getDigest();
115:         if (empty($digest)) {
116:             return false;
117:         }
118: 
119:         list(, $model) = pluginSplit($this->settings['userModel']);
120:         $user = $this->_findUser(array(
121:             $model . '.' . $this->settings['fields']['username'] => $digest['username']
122:         ));
123:         if (empty($user)) {
124:             return false;
125:         }
126:         $password = $user[$this->settings['fields']['password']];
127:         unset($user[$this->settings['fields']['password']]);
128:         if ($digest['response'] === $this->generateResponseHash($digest, $password)) {
129:             return $user;
130:         }
131:         return false;
132:     }
133: 
134: /**
135:  * Gets the digest headers from the request/environment.
136:  *
137:  * @return array Array of digest information.
138:  */
139:     protected function _getDigest() {
140:         $digest = env('PHP_AUTH_DIGEST');
141:         if (empty($digest) && function_exists('apache_request_headers')) {
142:             $headers = apache_request_headers();
143:             if (!empty($headers['Authorization']) && substr($headers['Authorization'], 0, 7) === 'Digest ') {
144:                 $digest = substr($headers['Authorization'], 7);
145:             }
146:         }
147:         if (empty($digest)) {
148:             return false;
149:         }
150:         return $this->parseAuthData($digest);
151:     }
152: 
153: /**
154:  * Parse the digest authentication headers and split them up.
155:  *
156:  * @param string $digest The raw digest authentication headers.
157:  * @return array|null An array of digest authentication headers
158:  */
159:     public function parseAuthData($digest) {
160:         if (substr($digest, 0, 7) === 'Digest ') {
161:             $digest = substr($digest, 7);
162:         }
163:         $keys = $match = array();
164:         $req = array('nonce' => 1, 'nc' => 1, 'cnonce' => 1, 'qop' => 1, 'username' => 1, 'uri' => 1, 'response' => 1);
165:         preg_match_all('/(\w+)=([\'"]?)([a-zA-Z0-9\:\#\%\?\&@=\.\/_-]+)\2/', $digest, $match, PREG_SET_ORDER);
166: 
167:         foreach ($match as $i) {
168:             $keys[$i[1]] = $i[3];
169:             unset($req[$i[1]]);
170:         }
171: 
172:         if (empty($req)) {
173:             return $keys;
174:         }
175:         return null;
176:     }
177: 
178: /**
179:  * Generate the response hash for a given digest array.
180:  *
181:  * @param array $digest Digest information containing data from DigestAuthenticate::parseAuthData().
182:  * @param string $password The digest hash password generated with DigestAuthenticate::password()
183:  * @return string Response hash
184:  */
185:     public function generateResponseHash($digest, $password) {
186:         return md5(
187:             $password .
188:             ':' . $digest['nonce'] . ':' . $digest['nc'] . ':' . $digest['cnonce'] . ':' . $digest['qop'] . ':' .
189:             md5(env('REQUEST_METHOD') . ':' . $digest['uri'])
190:         );
191:     }
192: 
193: /**
194:  * Creates an auth digest password hash to store
195:  *
196:  * @param string $username The username to use in the digest hash.
197:  * @param string $password The unhashed password to make a digest hash for.
198:  * @param string $realm The realm the password is for.
199:  * @return string the hashed password that can later be used with Digest authentication.
200:  */
201:     public static function password($username, $password, $realm) {
202:         return md5($username . ':' . $realm . ':' . $password);
203:     }
204: 
205: /**
206:  * Generate the login headers
207:  *
208:  * @return string Headers for logging in.
209:  */
210:     public function loginHeaders() {
211:         $options = array(
212:             'realm' => $this->settings['realm'],
213:             'qop' => $this->settings['qop'],
214:             'nonce' => $this->settings['nonce'],
215:             'opaque' => $this->settings['opaque']
216:         );
217:         $opts = array();
218:         foreach ($options as $k => $v) {
219:             $opts[] = sprintf('%s="%s"', $k, $v);
220:         }
221:         return 'WWW-Authenticate: Digest ' . implode(',', $opts);
222:     }
223: 
224: }
225: 
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