我使用Zend Rest Controller开发Web服务,现在我需要在用户访问我的页面之前对其进行身份验证。
为此,iam计划使用curl进行HTTP身份验证,如下所示:
curl_setopt($ch, CURLOPT_USERPWD, "myusername:mypassword");
我称之为卷曲页面:
curl -u myusername:mypassword http://localhost/controller/action/page.xml
我有一个很大的疑问。
我是否需要将用户名和密码存储在.htpasswd文件中?如果是这样,我如何检索参数并验证它们?
答案 0 :(得分:8)
如果你使用.htaccess,网络服务器将默默地为你处理一切。你可以假设(除非你犯了一个错误)该人被授权。
但是如果您想使用http auth并获取用户名和密码以在您自己的登录系统中使用,那么您需要编写如此处所示的被调用的脚本。
http://php.net/manual/en/features.http-auth.php
除了发送用户名和密码外,curl与它无关。它只是作为一个http客户端,就像一个webbrowser。
您如何执行身份验证归结为您要实现的目标。 http auth是一个简单的身份验证系统。
DC
我给你的链接告诉你如何做到这一点。您正在调用的页面必须发回一个身份验证请求,否则curl将不会转发身份验证详细信息。
如果您使用.htaccess和.htpasswd文件,则无法查看身份验证,因为Web服务器将删除这些标头。如果您正在使用我提供的链接中的自定义http身份验证,那么只有在发送身份验证请求后才能访问它们,这意味着第一次加载页面时您将无法获得它们。
我的意思是......首先curl要求没有任何凭据的页面,如果它获取页面然后停止,如果它获得凭据请求然后发送它们。
这意味着如果您希望http://localhost/controller/action/page.xml
查看凭据,则必须要求提供凭据。如果它是一个看起来像它的静态页面,那么它将不会要求提供凭据。
您的意思是键入http://localhost/controller/action/page.php
DC
这个过程是这样的......
curl ---> page.php (first request)
curl <--- page.php (first reply) "Please identify yourself" ('401 unauthorised' http code)
curl username:password ---> page.php (second request now includes user auth)
curl <--- page.php (second reply) ok here is the page (if id succesfull)
好的,如同承诺的一些工作实例
首先创建2个php脚本
auth.php是我在上面发布的链接
中提供的示例的修改副本<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo "User name and password is required. Please try again.\n";
} else {
// we now have access to the user and password :)
echo "Hello {$_SERVER['PHP_AUTH_USER']}\n";
echo "You entered {$_SERVER['PHP_AUTH_PW']} as your password.\n";
}
?>
curlfetch.php是您其他帖子的脚本副本
<?php
$curl = curl_init('http://localhost/auth.php');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_USERPWD, 'key:123456');
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_USERAGENT, 'Sample Code');
$response = curl_exec($curl);
$resultStatus = curl_getinfo($curl);
if($resultStatus['http_code'] == 200) {
echo $response;
} else {
echo 'Call Failed '.print_r($resultStatus);
}
?>
在您的服务器上创建并保存这些脚本
现在测试没有密码的脚本1
curl http://localhost/auth.php
这导致......
User name and password is required. Please try again.
现在尝试使用密码
curl -u user:pass http://localhost/auth.php
这导致......
Hello user
You entered pass as your password.
现在尝试第二个脚本,注意我们不提供脚本
中提供的用户名或密码curl http://localhost/curlfetch.php
导致......
Hello key
You entered 123456 as your password.
现在作为参考尝试从浏览器调用两个脚本
DC