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

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