PageRenderTime 44ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Controller/Component/Auth/DigestAuthenticate.php

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