【问题标题】:CakePHP: Auth error, even with allowed actionsCakePHP:身份验证错误,即使是允许的操作
【发布时间】:2012-04-05 19:28:40
【问题描述】:

在我的 Cake 应用程序中,我正在执行基本身份验证。我更喜欢保持简单和语义化(不喜欢 ACL),所以我只是检查用户的角色,并相应地允许或拒绝。

现在,授权所有功能都按预期进行,但我遇到了一个奇怪的问题,无论用户是否尝试允许的操作,Auth 错误消息都会显示。它在他们注销后仍然可见。

这是 AppController:

public $components = array(
    'Session',
    'Password',
    'Auth' => array(
        'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home'),
        'authError' => "Sorry, you're not allowed to do that.",
        'authorize' => array('Controller')
    ),
    'RequestHandler'
);

public function beforeFilter() {
    $this->set('loggedIn', $this->Auth->loggedIn());
    $this->set('current_user', $this->Auth->user());
    $this->set('admin', $this->_isAdmin());
    $this->set('coach', $this->_isCoach());
    $this->Auth->allow('login', 'logout', 'display');
}

public function isAuthorized($user) {
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true;
    }
    return false;
}

beforeFilter 和 isAuthorized 来自另一个控制器:

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

public function isAuthorized($user) {
    if ($user['role'] === 'coach') {
        if ($this->action === 'index') {
            return true;
        }
        if (in_array($this->action, array('view', 'edit', 'delete'))) {
            $id = $this->request->params['pass'][0];
            $this->User->id = $id;
            if ($this->User->field('client_id') === $user['client_id'] ) 
                return true;
            } else {
                return false;
            }
        }
        return false;
    }
    return parent::isAuthorized($user);
}

【问题讨论】:

    标签: cakephp authentication


    【解决方案1】:

    我决定改为在我的用户控制器中执行此操作,并且一切似乎都运行良好,而且它更干净/更具可读性:

    public function isAuthorized($user = null) {
        switch($this->action) {
            case "index":
            case "add":
                if ($user['role'] == 'coach') {
                    return true;
                }
                break;
    
            case "view":
            case "edit":
            case "delete":
                $id = $this->request->params['pass'][0];
                $this->User->id = $id;
                if ($user['role'] == 'coach' && $this->User->field('client_id') == $user['client_id']) {
                    return true;
                }
                break;
        }
        return parent::isAuthorized($user);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-17
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 2012-12-09
      • 2018-04-30
      • 1970-01-01
      • 2021-01-08
      相关资源
      最近更新 更多