【问题标题】:CakePHP: Prevent Auth component's "authError" message on homepageCakePHP:防止 Auth 组件在主页上出现“authError”消息
【发布时间】:2011-09-15 01:37:37
【问题描述】:

我有一个 CakePHP 项目,我在其中修改了“app/config/routes.php”,以便根指向“用户”控制器的“仪表板”操作。换句话说,这两个 URL 指向同一个地方:

http://example.com/

http://example.com/users/dashboard

我在“App”控制器中设置了“Auth”组件,如下所示:

class AppController extends Controller {
    var $components = array('Auth', 'Session');

    function beforeFilter() {
        $this->Auth->authorize = 'controller';
        $this->Auth->loginRedirect = array('controller' => 'users', 'action' => 'dashboard');

        if ($this->Auth->user()) {
            $this->set('logged_in', true);
        }
        else {
            $this->set('logged_in', false);
        }
    }
}

我希望这样,如果未经身份验证的用户直接访问 http://example.com/users/dashboard,他们会被带到登录页面 显示“Auth”组件的“authError”消息,但如果他们转到 http://example.com/ ,他们将被带到登录页面“Auth”组件的“authError”消息显示。这可能吗?

【问题讨论】:

    标签: cakephp


    【解决方案1】:

    我通过将以下代码放入“用户”控制器的“登录”操作中解决了这个问题:

    if ($this->Session->read('Auth.redirect') == $this->webroot && $this->Session->read('Message.auth.message') == $this->Auth->authError) {
        $this->Session->delete('Message.auth');
    }
    

    【讨论】:

      【解决方案2】:

      找这样的东西很久了!谢谢。

      我必须做一点改变,然后$this->webroot 不是“/”:

      if (str_replace("//","/",$this->webroot.$this->Session->read('Auth.redirect')) == $this->webroot && $this->Session->read('Message.auth.message') == $this->Auth->authError) {
          $this->Session->delete('Message.auth');
      }
      

      【讨论】:

        【解决方案3】:

        好吧,我不明白为什么有时您会显示错误,而有时为什么不显示。但是您可以负担得起创建 isAuthorized 方法并修改默认 AuthComponent 行为的所有逻辑的费用。

        打开您的 Auth 组件并检查方法“startup()”。在那里,在最后一行,你会看到这个:

        $this->Session->setFlash($this->authError, $this->flashElement, array(), 'auth');
        $controller->redirect($controller->referer(), null, true);
        

        这是负责显示错误的部分。

        在此之前,你会看到...

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

        因此,您可以更改您的 isAuthorized 方法,以便在需要时更改此消息。

        (我认为..)没有很多工作。

        附言。可能有更简单的方法可以忽略我

        【讨论】:

        • 感谢您的建议!想想看。有人访问您的网站主页,他们看到的第一件事就是一条消息,上面写着“访问被拒绝”。在我看来,不是很友好。
        【解决方案4】:

        如果你真的想阻止主页上的authError消息并简单地重定向到登录页面,那么你必须将false作为authError的参数

        class AppController extends Controller {
        
            public function initialize() {
                parent::initialize();
        
                $this->loadComponent('RequestHandler');
                $this->loadComponent('Flash');
                $this->loadComponent('Auth', [
                    'authError' => false
                ]);
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-10-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-01-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多