Authorize users based on roles in CakePHP 3

人走茶凉 提交于 2019-12-05 02:34:22

问题


I would like to authorize users based on few roles. All visitors should be able to reach method show. So I wrote in AppController:

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

It works.

In initialize() method of AppController I've got also:

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

I would like to allow logged users with role "user" to reach all "index", and "add" methods, so I wrote in 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;
}

Admin can reach all methods as expected. User logged with role "user" can't reach "index" or "add" method. How can I fix this?


回答1:


Instead of using your logic to add additional Auth allows, just use the logic to determine if they're in an action they're allowed, by checking the action, and return true if they're authorized.

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

(obviously this code could be shortened to your liking, but it shows the concept)




回答2:


I find this solution to be great and easier to maintain.

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


来源:https://stackoverflow.com/questions/39645441/authorize-users-based-on-roles-in-cakephp-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!