根据CakePHP 3中的角色授权用户 [英] Authorize users based on roles in CakePHP 3

查看:59
本文介绍了根据CakePHP 3中的角色授权用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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']);
}

它有效。

在AppController的initialize()方法中,我也得到了:

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

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

我希望允许角色为 user的登录用户访问所有 index,并且添加方法,因此我在AppController中写道:

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?

推荐答案

不是使用您的逻辑来添加其他Auth允许,而是使用逻辑来确定它们是否通过检查动作,允许他们执行动作,如果得到授权,则返回 true

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)

这篇关于根据CakePHP 3中的角色授权用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆