据我所知,唯一的方法是创建一个来宾用户。这是因为 Auth 组件在isAuthorized()
像您解释的那样之前检查用户的存在。
您可以通过直接写入会话来做到这一点。这将告诉 Auth 组件有人登录,因此isAuthorized()
将调用您的方法。
应用控制器
public function beforeFilter() {
// if no one is logged in, log in a guest
if (!$this->Auth->user()) {
$this->Session->write(AuthComponent::$sessionKey, array(
'User' => array(
'id' => 0
)
));
}
}
public function isAuthorized($user) {
$authorized = false;
if ($this->Auth->user('id') == 0) {
// public guest user access
}
// other logic
return $authorized;
}
一个可能更好的方法是使用自定义身份验证对象,它基本上告诉 Cake 使用该类来帮助进行身份验证。这会将逻辑拆分为一个单独的类,从而更容易测试甚至禁用。
应用程序/控制器/组件/Auth/GuestAuthenticate.php
App::uses('BaseAuthenticate', 'Controller/Component/Auth');
class GuestAuthenticate extends BaseAuthenticate {
public function authenticate(CakeRequest $request, CakeResponse $response) {
// no real authentication logic, just return a guest user
return array('User' => array('id' => 0));
}
}
应用控制器
public $components = array(
'Auth' => array(
'authenticate' => array(
'Form',
'Guest' // tell Cake to try Form authentication then Guest authentication
)
)
);
public function beforeFilter() {
if (!$this->Auth->user()) {
// no user? log in a guest (this will fail form authentication
// then try guest authentication)
$this->Auth->login();
}
}
public function isAuthorized($user) {
$authorized = false;
if ($this->Auth->user('id') == 0) {
// public guest user access
}
// other logic
return $authorized;
}
您可以在此处找到有关自定义身份验证对象的更多信息:http: //book.cakephp.org/2.0/en/core-libraries/components/authentication.html