CakePHP2.5。Auth Basic:未经授权的错误时重定向
我有一个API,其中我使用Auth进行基本身份验证。 只要我使用正确的用户名和密码,一切都会顺利 现在我去看看如果我用错误的数据登录会发生什么 我收到错误消息:CakePHP2.5。Auth Basic:未经授权的错误时重定向,cakephp,authentication,Cakephp,Authentication,我有一个API,其中我使用Auth进行基本身份验证。 只要我使用正确的用户名和密码,一切都会顺利 现在我去看看如果我用错误的数据登录会发生什么 我收到错误消息: Unauthorized Error: The requested address '/api' was not found on this server. 有什么我能做的,我可以退一张票吗 $this->response->statusCode(401); 而不是别的什么? 我以为我有其他的情况,但一个(见下文)是
Unauthorized
Error: The requested address '/api' was not found on this server.
有什么我能做的,我可以退一张票吗
$this->response->statusCode(401);
而不是别的什么?
我以为我有其他的情况,但一个(见下文)是没有得到呼吁。。。
我不知道为什么
我的代码如下所示:
var $components = array('Auth' => array(
'loginAction' => array(
'controller' => 'api',
'action' => 'login'
),
'authenticate' => array(
'Basic' => array(
'userModel' => 'Appuser'
)
)));
public function login() {
$this->autoRender = false;
if ($this->Auth->login()) {
$this->Appuser->id = AuthComponent::user('id');
// save last login
$this->Appuser->saveField('last_login', date("Y-m-d H:i:s"));
return $this->response->body(json_encode('Hello :-) You are in!'));
}else{
return $this->response->body(json_encode(array('ERROR' => array('file' => basename(__FILE__), 'line' => __LINE__, 'msg'=> 'Login failed!'))));
}
这不是一个直接的回应,但在我的申请中,我做了这样的事情,希望它能帮助你:
public $components = array(
'Session',
'Auth'=>array(
'loginRedirect' => array('controller' => 'projets', 'action' => 'index', 'admin'=>true),
'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'admin'=>false, 'intro'),
'loginError' => "Les informations d'identification sont incorrectes.",
)
);
好的,我发现了:
首先,我必须添加到我的API中
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('login');
}
然后我学习了本教程:
以及在app/Lib/Error/AppExceptionRenderer.php中
我补充说
public function notAuth($error) {
$this->controller->beforeFilter();
$this->controller->response->send(401);
}
public function unauthorized($error) {
$this->notAuth($error);
}
这样,当我试图使用错误的数据进入API时,API的每个函数都会出现401错误,当我直接调用登录函数时,我将if($This->Auth->login())的“else”设置为$This->response->statusCode(401) 尝试未经授权的直接:
AuthComponent::$unauthorizedRedirect
由于我想从移动设备连接到api,只要使用正确的数据登录,我就不需要这些重定向。我想知道为什么我得到这个未经授权,而不是从$this->Auth->login()函数得到else。现在的问题是,我的设备接收到一大堆html响应,其中显示未经授权的内容。在这种情况下,我想要呈现任何东西,只是一个简单的返回消息,说登录失败…虽然答案包含在链接中,但答案也包含在链接中断时web搜索可能包含的关键字中。