【问题标题】:Why is the logout action not accessible?为什么无法访问注销操作?
【发布时间】:2026-01-31 11:35:02
【问题描述】:

我想让Auth 访问我的用户控制器的login()logout()add() 操作,但我是否使用$this->Auth->allow('logout'); 并不重要,我会收到消息:@ 987654326@ login()add() 工作正常。

这是我的 AppContoller.php:

class AppController extends Controller {

    public $components = array(

        'Auth' => array(
            'authenticate' => array(
                'Form' => array(
                    'userModel' => 'User',
                    'fields' => array(
                    'username' => 'email', 'password' => 'password')
                    )

            ), 

            'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
            'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'landing')
        ), 'Session'
    );

    public function beforeFilter() {
        $this->Auth->allow('add', 'login');
    }

}

这是我的 UsersController.php 的相关部分:

    public $helpers = array('Html', 'Form', 'Session');
    public $components = array('Session');


    public function beforeFilter() {

        parent::beforeFilter();
        $this->Auth->allow('logout');

    }
    public function logout() {
        $this->set('title_for_layout', 'Logout');
        $this->redirect($this->Auth->logout());
    }

有人看到这里的问题吗?感谢您的帮助。

【问题讨论】:

  • 快速浏览一下我可以看到一个小问题,在重定向之前设置标题是没有意义的,尽管它不应该成为您的问题的一个因素。您重定向到的页面是 Auth->allowed?
  • @Daniel,是的,正如您在 UserController.php 的 beforeFilter 函数中看到的那样,它是允许身份验证的。
  • 抱歉,我的意思是 logoutRedirect 操作 - /pages/display/landing。

标签: php authentication cakephp-2.0 logout


【解决方案1】:

您似乎可以毫无问题地访问注销操作,但注销重定向会破坏您的会话并将您重定向到 page 视图。

您似乎无法在未登录的情况下访问该页面。 (您可以尝试在不登录的情况下访问该 URL)

在您的PagesController 中添加beforeFilter 函数:

public function beforeFilter(){
    parent::beforeFilter();

    $this->Auth->allow();
}

CakePHP 2.2 默认自带PagesController,如果没有,只需复制并粘贴任何其他控制器并添加此功能即可删除所有其他控制器。

编辑: 如果 PagesController 已经存在,只需添加 beforeFilter 函数。

【讨论】:

  • 哦,太好了,在确定问题后,我显然得到了答案。谢谢。
  • 能否请您点击我的答案左侧的票将答案标记为有效?
  • 不要,至少在它被编辑之前不要——史蒂夫关于从 PagesController 中删除功能的建议很糟糕,它删除了提问者显然依赖于使用的显示操作。
  • 我不是在谈论删除显示操作或 PagesController 中的任何内容。我说的是删除这些东西,以防他复制并粘贴另一个控制器来创建这个(因为如果我记错了,它不是在其他 CakePHP 版本中默认创建的)(抱歉,我没有阅读你的评论问题)。无论如何,我会澄清它......
  • 大部分答案都很好,只是这一行“添加此功能删除所有其余部分”。问题是在 /app/Controllers 中的 PagesController 中删除会覆盖 Cake 使用的那个。因此,他的 PagesController 中也需要一个 display() 函数。