我使用yii框架准备了一个api。 api包含一个身份验证方法,该方法检查HTTP_X_USERNAME和HTTP_X_PASSWORD参数,并将它们与数据库中的某些数据进行比较。
在测试开发(WAMP + Eclipse + Tomcat)上本地测试所有内容时,它正常工作。我用邮递员测试了一切。我已将这两个参数(HTTP_X _...)放入标题中。
将api上传到生产服务器(Tomcat)之后,尽管本地和在线的授权数据相同,但api始终返回FALSE认证。代码在检查这些参数是否被设置的部分停止“您必须被授权访问api。没有设置USERNAME和PASSWORD。”。
有没有人知道问题出在哪里?为什么它在本地工作而不是在线???
private function _checkAuth() {
$headers = apache_request_headers ();
if (! (isset ( $headers ['HTTP_X_USERNAME'] ) and isset ( $headers ['HTTP_X_PASSWORD'] ))) {
// Error: Unauthorized
$this->badResponse ( 401, 'You must be authorized to access the api. No USERNAME and PASSWORD set.');
}
$username = $headers ['HTTP_X_USERNAME'];
$password = $headers ['HTTP_X_PASSWORD'];
// Find the user
$criteria = new CDbCriteria ();
$criteria->addCondition ( 'email = :email');
$criteria->addCondition( 'api_access_token = :pass');
$criteria->params = array(':email' => $username, ":pass" => $password);
$school = AutoSchool::model ()->find ( $criteria );
if ($school === null) {
$this->badResponse ( 401, 'Error: You must be authorized to access the api.' );
}
return $school->id;
}
答案 0 :(得分:0)
终于找到了问题!
在debuging发现问题是方法apache_request_headers(),因为它没有返回我在标题中设置的任何有用的东西。
我实现了自己的方法
private function apache_request_headers2() {
foreach($_SERVER as $key=>$value) {
if (substr($key,0,5)=="HTTP_") {
$key=str_replace(" ","-",ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
$out[$key]=$value;
}else{
$out[$key]=$value;
}
}
return $out;
}
但这不是全部。我不得不更改我请求的标头参数。我不得不使用$ headers [' PHP_AUTH_USER']和$ headers [' PHP_AUTH_PW']而不是HTTP_X_USERNAME和HTTP_X_PASSWORD。
最后,在发出POST请求时,我必须使用基本身份验证而不是设置标头参数
编辑方法的完整代码:
private function _checkAuth() {
$headers = $this->apache_request_headers2();
if (! (isset ( $headers ['PHP_AUTH_USER'] ) and isset ( $headers ['PHP_AUTH_PW'] ))) {
// Error: Unauthorized
$this->badResponse ( 401, 'You must be authorized to access the api. No USERNAME and PASSWORD set.');
}
$username = $headers ['PHP_AUTH_USER'];
$password = $headers ['PHP_AUTH_PW'];
// Find the user
$criteria = new CDbCriteria ();
$criteria->addCondition ( 'email = :email');
$criteria->addCondition( 'api_access_token = :pass');
$criteria->params = array(':email' => $username, ":pass" => $password);
$school = AutoSchool::model ()->find ( $criteria );
if ($school === null) {
$this->badResponse ( 401, 'Error: You must be authorized to access the api.' );
}
return $school->id;
}