所以我决定对我的REST API使用摘要HTTP身份验证.我已经在Google手册中找到了一个条目,并提供了一个如何做的例子.所以我复制脚本,将其放在我的服务器上的index.PHP中,在浏览器中打开页面,输入我的凭据后,浏览器再次询问他们,并且我被卡入无限循环的输入凭证.脚本包含在下面,可以找到
here.
示例#7摘要HTTP验证示例
<?PHP $realm = 'Restricted area'; //user => password $users = array('admin' => 'mypass','guest' => 'guest'); if (empty($_SERVER['PHP_AUTH_DIGEST'])) { header('HTTP/1.1 401 Unauthorized'); header('WWW-Authenticate: Digest realm="'.$realm. '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"'); die('Text to send if user hits Cancel button'); } // analyze the PHP_AUTH_DIGEST variable if (!($data = http_digest_parse($_SERVER['PHP_AUTH_DIGEST'])) || !isset($users[$data['username']])) die('Wrong Credentials!'); // generate the valid response $A1 = md5($data['username'] . ':' . $realm . ':' . $users[$data['username']]); $A2 = md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']); $valid_response = md5($A1.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.$A2); if ($data['response'] != $valid_response) die('Wrong Credentials!'); // ok,valid username & password echo 'Your are logged in as: ' . $data['username']; // function to parse the http auth header function http_digest_parse($txt) { // protect against missing data $needed_parts = array('nonce'=>1,'nc'=>1,'cnonce'=>1,'qop'=>1,'username'=>1,'uri'=>1,'response'=>1); $data = array(); $keys = implode('|',array_keys($needed_parts)); preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@',$txt,$matches,PREG_SET_ORDER); foreach ($matches as $m) { $data[$m[1]] = $m[3] ? $m[3] : $m[4]; unset($needed_parts[$m[1]]); } return $needed_parts ? false : $data; } ?>
我也尝试过基本身份验证,并且工作完美.
示例#6基本HTTP身份验证示例
<?PHP if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="My Realm"'); header('HTTP/1.0 401 Unauthorized'); echo 'Text to send if user hits Cancel button'; exit; } else { echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>"; echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>"; } ?>
似乎$_SERVER [‘PHP_AUTH_DIGEST’]始终为空.
脚本有问题吗或者我的环境好吗?如果是这样,我该怎么解决?
编辑:脚本没有错.服务器出现故障.如果有人知道可能导致什么,请让我知道.
摘要认证是一个单独的Apache模块,通常不会安装在服务器上 – 特别是与廉价的托管公司.它需要启用才能使用它.
http://httpd.apache.org/docs/current/mod/mod_auth_digest.html
这取决于您的发行版如何安装,如果您使用的是Linux.在我的Ubuntu Linux上,可以从模块的停用模块文件夹到激活的模块创建一个符号链接,一个在shell上运行sudo a2enmod auth_digest.那当然是重启Apache了.
我不知道Windows.