【问题标题】:CakePHP3 BeforeFilter & Auth RedirectCakePHP3 BeforeFilter 和 Auth 重定向
【发布时间】:2016-10-15 20:00:28
【问题描述】:

谁能帮我理解 Cakephp 3.3 的处理以及我遇到的 BeforeFilter/Auth Redirect 问题。

我正在使用默认的 Auth 组件。我创建了一个自定义组件,该组件还检查会话变量(注册),如果未设置该变量,则重定向到旨在进行选择以设置所需注册的页面。

这是我的自定义组件:

<?php

namespace App\Controller\Component;

use Cake\Controller\Component;
use Cake\Network\Request;


class RegistrationCheckComponent extends Component
{

private $_allowedActions = [];
private $_superUserBypass = false;

public $components = ['Auth'];

public function superUserBypass($val = false) {
    $this->_superUserBypass = $val;
}

public function allow(Array $allowedActions = []) {
    $this->_allowedActions = $allowedActions;
}

public function verify() {

    if($this->_superUserBypass) {
        return true;
    }

    $session = $this->request->session();
    //if Auth Registration is not set
    if(!$session->read('Auth.Registration')) {
        //if requested action is not in the array of allowed actions, redirect to select registration
        if(!in_array($this->request->param('action'), $this->_allowedActions)) {
            return $this->redirect();
        };
        return true;
    }
    return true;

}

public function redirect() {
    $controller = $this->_registry->getController();
    return $controller->redirect($this->config('redirect'));
}

}

并非所有控制器都需要设置 Registration 变量,这就是我决定采用组件方法的原因。然而,该组件是通过这一行加载到 AppController 中的:

$this->loadComponent('RegistrationCheck', ['redirect' => ['controller' => 'Users', 'action' => 'registrations']]);

在需要设置 Registration 变量的控制器中,我包含以下 beforeFilter 函数:

public function beforeFilter(Event $event) {
    parent::beforeFilter($event);
    return $this->RegistrationCheck->verify();
}

现在,我已经定义了一些集成测试,这是其中之一:

public function testUnauthenticatedEdit()
{
    $this->get('/teams/edit');
    $this->assertRedirect(['controller' => 'Users', 'action' => 'login']);
}

所以,在我实现了我的 RegistrationCheck 组件之后,我运行了集成测试。我原以为考试会通过,但没有。有趣的是,它实际上返回了对用户->注册的重定向,而不是我预期的用户->登录。

在我看来,RegistrationCheck 重定向发生在 Auth 组件重定向之前。我不确定这是什么大不了的事,因为在没有设置身份验证的情况下重定向到注册最终会重定向回登录,但忽略它似乎是不正确的......另外,我只是想了解更多实际发生的事情。

任何人都可以建议对我的代码进行更改以确保在 RegistrationCheck 组件之前处理 Auth 组件吗?

提前致谢。

【问题讨论】:

    标签: authentication cakephp-3.x before-filter


    【解决方案1】:

    好吧,经过一番研究,我在这里找到了我正在寻找的答案:http://book.cakephp.org/3.0/en/controllers/components/authentication.html#deciding-when-to-run-authentication

    真的很简单,只是想在这里为任何可能偶然发现相同问题的人提供答案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-01
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多