1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18:
19:
20: 21: 22: 23: 24:
25: class DigestAuthentication {
26:
27: 28: 29: 30: 31: 32: 33: 34:
35: public static function authentication(HttpSocket $http, &$authInfo) {
36: if (isset($authInfo['user'], $authInfo['pass'])) {
37: if (!isset($authInfo['realm']) && !self::_getServerInformation($http, $authInfo)) {
38: return;
39: }
40: $http->request['header']['Authorization'] = self::_generateHeader($http, $authInfo);
41: }
42: }
43:
44: 45: 46: 47: 48: 49: 50:
51: protected static function _getServerInformation(HttpSocket $http, &$authInfo) {
52: $originalRequest = $http->request;
53: $http->configAuth(false);
54: $http->request($http->request);
55: $http->request = $originalRequest;
56: $http->configAuth('Digest', $authInfo);
57:
58: if (empty($http->response['header']['WWW-Authenticate'])) {
59: return false;
60: }
61: preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $http->response['header']['WWW-Authenticate'], $matches, PREG_SET_ORDER);
62: foreach ($matches as $match) {
63: $authInfo[$match[1]] = $match[2];
64: }
65: if (!empty($authInfo['qop']) && empty($authInfo['nc'])) {
66: $authInfo['nc'] = 1;
67: }
68: return true;
69: }
70:
71: 72: 73: 74: 75: 76: 77:
78: protected static function _generateHeader(HttpSocket $http, &$authInfo) {
79: $a1 = md5($authInfo['user'] . ':' . $authInfo['realm'] . ':' . $authInfo['pass']);
80: $a2 = md5($http->request['method'] . ':' . $http->request['uri']['path']);
81:
82: if (empty($authInfo['qop'])) {
83: $response = md5($a1 . ':' . $authInfo['nonce'] . ':' . $a2);
84: } else {
85: $authInfo['cnonce'] = uniqid();
86: $nc = sprintf('%08x', $authInfo['nc']++);
87: $response = md5($a1 . ':' . $authInfo['nonce'] . ':' . $nc . ':' . $authInfo['cnonce'] . ':auth:' . $a2);
88: }
89:
90: $authHeader = 'Digest ';
91: $authHeader .= 'username="' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $authInfo['user']) . '", ';
92: $authHeader .= 'realm="' . $authInfo['realm'] . '", ';
93: $authHeader .= 'nonce="' . $authInfo['nonce'] . '", ';
94: $authHeader .= 'uri="' . $http->request['uri']['path'] . '", ';
95: $authHeader .= 'response="' . $response . '"';
96: if (!empty($authInfo['opaque'])) {
97: $authHeader .= ', opaque="' . $authInfo['opaque'] . '"';
98: }
99: if (!empty($authInfo['qop'])) {
100: $authHeader .= ', qop="auth", nc=' . $nc . ', cnonce="' . $authInfo['cnonce'] . '"';
101: }
102: return $authHeader;
103: }
104:
105: }
106: