在CakePHP 3中基于角色授权用户

3

我希望可以根据几种角色授权用户访问权限。所有来访者都应该能够访问show方法。因此我在AppController中编写了如下代码:

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

它能工作。

在AppController的initialize()方法中,我还有以下代码:

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

我想允许角色为“用户”的已登录用户访问所有的“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;
}

管理员可以按预期访问所有方法。以“用户”角色登录的用户无法访问“index”或“add”方法。我该怎么解决这个问题?


你可以尝试使用TinyAuth,它可以在不需要在控制器中编写代码的情况下解决这个问题 :) - mark
2个回答

11

不要使用逻辑来添加额外的身份验证,而是使用逻辑来确定他们是否在允许的操作中,通过检查操作来返回 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;
}

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


1
嘿,我仍然无法投票,但是你的答案帮了我很多。谢谢! - nexequ

0

我认为这个解决方案非常好,而且更易于维护。

//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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接