【问题标题】:cakePHP authentication problemscakePHP认证问题
【发布时间】:2012-05-29 18:09:28
【问题描述】:

我无法理解 Auth 组件在 cakePHP 中的工作原理。我正在使用 2.1

我的登录工作完美,据我了解,我可以在 appController 中设置默认组件,如下所示。

 // App controller:

 public $components = array(
    'Session',

    'Auth' => array(
        'loginAction' => array(
            'controller' => 'users',
            'action' => 'login',
        ),
        'authError' => "Your username and password is incorrect, please try again.",
        'authenticate' => array(
            'Form' => array(
                'scope' => array('User.user_status_id' => 1)
            )
        ),
        'redirect' => array("controller" => "users", "action" => "profile"),
        'loginRedirect' => array("controller" => "users", "action" => "profile")
    )
);

public function beforeFilter() {
    $this->Auth->allow("home");
   if($this->Auth->loggedIn() == true) {
       $this->set("user_name",$this->Auth->user("first_name")." ".$this->Auth->user("last_name"));
       $this->set("loggedIn",true);
       if($this->Auth->user("user_type_id") == 5) {
           $this->set("navigation","navigation_admin");
       } else {
           $this->set("navigation","navigation_loggedin");
       }
   } else {
       $this->set("loggedIn",false);
       $this->set("navigation","navigation_notloggedin");
   }

}

home 位于 /app/view/home.ctp,但是,我无法在未登录的情况下访问该页面。接下来我有 2 个不同的用户级别,普通用户和管理员。我想根据您是否是管理员来限制控制器中的某些操作。

在我的 UserController 我有例子:

 public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow("login");
    if($this->Auth->user("user_type_id") != 5) {
        $this->Auth->allow("login","profile");
    }
}

但无论用户类型如何,每个人都可以查看操作。

在我的页面控制器中,我还有以下内容:

 public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow("*");
    }

但我必须登录才能查看任何页面。

我确信我做错了什么,但我无法理解是什么,有什么帮助吗?

【问题讨论】:

  • app/view/home.ctp?你的意思是app/view/pages/home.ctp?

标签: php cakephp authentication controller


【解决方案1】:

首先,home 不是控制器上的操作,因此$this->Auth->allow("home"); 不会产生影响。 $this->Auth->allow("display"); 将允许查看所有页面(不确定是否有意)。

其次,你使用$this->Auth->allow("*"); after 你调用了父级的beforeFilter,这意味着AppController::beforeFilter() 将把它当作用户没有登录,因为它不知道事后你所允许的。

【讨论】:

  • 这看起来像原因,isAllowed 在 beforeFilter by auth by $this->allowedActions == array('*') || in_array($action, array_map('strtolower', $allowedActions)) 之后被检查,在这种情况下既不是因为$allowedActions 看起来像array('home', '*') 我想。
  • @Jeremy:谢谢,这解决了我的页面问题。我在 appcontroller 中更改了 $this->Auth->allow("display"),它的作用就像一个魅力来显示所有页面。然而,我仍然发现在我的用户控制器(如上)中,即使有 if 语句,我也无法阻止普通用户访问添加页面,即使我使用拒绝(“添加”)
  • 那是因为 Auth->allow 在用户登录后没有任何影响。最简单的方法是将 Auth 设置为 authroize Controller 并实现 isAuthorized() 方法。有关示例,请参阅本书。
  • 同意@tigrang。对于更复杂的身份验证,实现isAuthorized()book.cakephp.org/2.0/en/tutorials-and-examples/…
猜你喜欢
  • 2012-01-18
  • 1970-01-01
  • 2011-02-02
  • 1970-01-01
  • 2011-07-07
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 1970-01-01
相关资源
最近更新 更多