我在一个简单的 CakePHP 2.0 应用程序中设置了基本身份验证。我首先将应用程序设置为使用常规表单例份验证,然后将以下行添加到 AppController.php 的 beforeFilter()
以启用基本的 http 身份验证:
$this->Auth->authenticate = array('Basic');
这是完整的 AppController:
<?php
class AppController extends Controller {
public $components = array(
"Session",
"Auth" => array(
'loginRedirect' => array('controller'=>'users','action'=>'index'),
'logoutRedirect' => array('controller'=>'users','action'=>'index'),
'authError' => "You are not authorized to view this page.",
'authorize' => array('Controller'),
)
);
public function isAuthorized($user) {
return true;
}
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('index','view');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user',$this->Auth->user());
$this->Auth->authenticate = array('Basic');
}
}
?>
理想情况下,我希望整个应用程序中的一个特定 Controller (一个将公开用于移动设备的 API 的 Controller )仅使用基本 HTTP 身份验证,而其余 Controller 的行为类似于普通网络申请。
目前,如果我将不正确的凭据传递给 Controller ,我会收到 HTTP 302 响应,而我真的希望传回 HTTP 401。我该怎么做?
*因打字错误而编辑
最佳答案
public function beforeFilter() {
parent::beforeFilter();
$this->Auth->allow('index','view');
$this->set('logged_in', $this->Auth->loggedIn());
$this->set('current_user',$this->Auth->user());
if($this->name == 'Specific') {
// for the specific controller
$this->Auth->authenticate = array('Basic');
} else {
// everything else
}
}
检查 KVZ 的 rest 插件可能会感兴趣 https://github.com/kvz/cakephp-rest-plugin
关于php - CakePHP 2.0 基本身份验证始终提供 302 重定向而不是 401 未授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9271802/