根据 CakePHP 3 中的角色授权用户

Authorize users based on roles in CakePHP 3

我想根据几个角色授权用户。所有参观者都应该能够到达方法展示。所以我在 AppController 中写道:

public function beforeFilter(Event $event) {
    $this->Auth->allow(['show']);
}

有效。

在 AppController 的 initialize() 方法中我还有:

$this->loadComponent('Auth', [
    'authorize' => 'Controller'
]);

我想允许具有 "user" 角色的登录用户访问所有 "index" 和 "add" 方法,所以我在 AppController 中写道:

public function isAuthorized($user) {
if (isset($user['role']) && $user['role'] === 'admin') {
return true;
}
if (isset($user['role']) && $user['role'] === 'user') {
$this->Auth->allow(['index', 'logout', 'add']);
}

return false;
}

管理员可以按预期访问所有方法。使用 "user" 角色登录的用户无法访问 "index" 或 "add" 方法。我该如何解决这个问题?

不是使用您的逻辑来添加额外的 Auth 允许,而是使用逻辑来确定他们是否在他们被允许的操作中,通过检查操作和 return true如果他们被授权。

public function isAuthorized($user) {

    // Admin allowed anywhere
    if (isset($user['role']) && $user['role'] === 'admin') {
        return true;
    }

    // 'user' allowed in specific actions
    if (isset($user['role']) && $user['role'] === 'user') {

        $allowedActions = ['index', 'logout', 'add'];
        if(in_array($this->request->action, $allowedActions)) {
            return true;
        }

    }
    return false;
}

(显然这段代码可以根据您的喜好缩短,但它展示了概念)

我觉得这个解决方案很棒而且更容易维护。

//in all controllers that you want to restrict access
public function isAuthorized($user)
{
    //an array since we might want to add additional roles
    $possibleRoles = array('admin');
    return $this->confirmAuth($user['role'], $possibleRoles);
}

//in AppController
public function confirmAuth($userRole, $allowedRoles)
{
    return in_array($userRole, $allowedRoles);
}