【问题标题】:Cakephp 2.6 : Role wise isAuthorized not workingCakephp 2.6:角色明智的isAuthorized不起作用
【发布时间】:2015-12-13 17:16:49
【问题描述】:

我在UsersController 中有几种方法,我正在尝试赋予角色明智的访问权限。 如果

  1. user_types == 1(用户可以访问所有方法)
  2. user_types == 2(用户无法访问admin_list方法。
  3. user_types == 3(用户只能访问forget_password方法)

在控制器中我尝试了下面的代码

public $components = array('Session','RequestHandler','Auth'=>array(

            'loginRedirect' => array('controller' => 'users','action' => 'dashboard'),
            'logoutRedirect' => array('controller' => 'users','action' => 'login'),
            'authError'=>'You can not access this page!!',
            'authenticate' => array(
            'Form' => array(
                'fields' => array(
                  'username' => 'email', //Default is 'username' in the userModel
                  'password' => 'password'  //Default is 'password' in the userModel
                )
              ),
            ),
            'authorize' => array('Controller')
        ));

        public function isAuthorized($user) {
            return true;
        }

在过滤器之前我允许

    $this->Auth->allow('login','logout');

现在在UserController我尝试了下面的代码

public function isAuthorized($user) {
    // Admin can access every action
    if (isset($user['usertype_id']) && $user['usertype_id'] == 1) {
            return true;
    }
    else if(isset($user['usertype_id']) && $user['usertype_id'] == 2)
    {
         $this->Auth->deny('admin_list');
    }else
        $this->Auth->allow('change_password');

    return parent::isAuthorized($user);
    }

问题是它总是返回 true。如果我使用 user_type = 3 登录,我可以访问所有方法。

【问题讨论】:

    标签: cakephp cakephp-2.6


    【解决方案1】:

    Auth::allow()Auth::deny() 旨在定义哪些操作允许非登录用户访问(身份验证),并且不用于授权。

    为此,您必须在控制器中定义isAuthorized(),就像您所做的那样。但是,这个方法预计会返回true(登录的用户/组被授权访问操作)或false(授权被拒绝)。

    您的UsersController::isAuthorized() 方法应改写为:

    public function isAuthorized($user) {
    
        if (!isset($user['usertype_id'])) {
            return false;
        }
    
        if($user['usertype_id'] == 2 && $this->action=='admin_list') {
           return false;           
        }
    
        if($user['usertype_id'] == 3) && $this->action!='forget_password'){
            return false;
        }
    
        return true;
    }
    

    有关更多信息,请参阅食谱ControllerAuthorize

    【讨论】:

    • 现在可以正常使用了,是否可以使用 inArray() 来实现这个条件?
    • 当然。您可以将一系列操作传递给in_array()
    • 如果你不介意可以给我一个例子吗?
    • 为了能够提供一个例子,我需要确切地知道你期望它做什么。请注意in_array() 等价于逻辑OR,并且您的用户类型/操作矩阵很容易变得非常复杂。如果您发现自己处于这种情况,您可能需要改用AclComponent。你在isAuthorized() 中输入什么并不重要,只要它按预期返回truefalse
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2012-03-20
    • 2015-04-02
    • 2018-10-02
    相关资源
    最近更新 更多